创建 准备好的 请求; 您可以在创建主体之后在其中添加标题:
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))