创建 准备好的
请求; 您可以在创建主体之后在其中添加标题:
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摘要中使用的秘密。您还可以传入其他标题名称。



