您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

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

import requests
import hmac
import hashlib


request = 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 count
import time

# store as a global variable
NONCE_COUNTER = count(int(time.time() * 1000))

# then every time you create a request
payload['nonce'] = next(NONCE_COUNTER)

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

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

import hmac
import hashlib

class 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.encode('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摘要中使用的秘密。您还可以传入其他标题名称

python 2022/1/1 18:26:56 有183人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶