栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用HMAC-SHA512和Python请求库签署POST请求?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用HMAC-SHA512和Python请求库签署POST请求?

创建 准备好的
请求
; 您可以在创建主体之后在其中添加标题:

import requestsimport hmacimport hashlibrequest = requests.Request(    'POST', 'https://poloniex.com/tradingApi',    data=payload, headers=headers)prepped = request.prepare()signature = hmac.new(secret, prepped.body, digestmod=hashlib.sha512)prepped.headers['Sign'] = signature.hexdigest()with requests.Session() as session:    response = session.send(prepped)

我改变了你的

params
观点
data
; 对于POST请求,通常在正文中发送参数,而不是在URL中发送。

对于随机数,我将使用从当前时间播种的

itertools.count()
object,因此重新启动不会影响它。根据Poloniex
API文档(在问题中引用的内容),随机数是POST主体的一部分,而不是标头,因此将其放在
payload
字典中:

from itertools import countimport time# store as a global variableNONCE_COUNTER = count(int(time.time() * 1000))# then every time you create a requestpayload['nonce'] = next(NONCE_COUNTER)

int(time.time())
如果您每秒创建多个请求,则使用将重复使用相同的数字。在由Poloniex提供的示例代码的用途
int(time.time()*1000)
,以使其能够创建请求每微秒,而不是,而是用自己的单调递增计数器(从种子
time.time()
)是稳健得多。

您还可以将摘要签名过程封装在自定义身份验证对象中;在准备好的请求中传递这样的对象,作为准备的最后一步:

import hmacimport hashlibclass BodyDigestSignature(object):    def __init__(self, secret, header='Sign', algorithm=hashlib.sha512):        self.secret = secret        self.header = header        self.algorithm = algorithm    def __call__(self, request):        body = request.body        if not isinstance(body, bytes):   # Python 3 body = body.enpre('latin1')  # standard encoding for HTTP        signature = hmac.new(self.secret, body, digestmod=self.algorithm)        request.headers[self.header] = signature.hexdigest()        return request

将此与您的

requests
电话一起使用:

response = requests.post(    'https://poloniex.com/tradingApi',    data=payload, headers=headers, auth=BodyDigestSignature(secret))

传入的参数是HMAC摘要中使用的秘密。您还可以传入其他标题名称。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/651711.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号