我正在尝试运行类似于此问题中的代码:How do I sign a POST request using HMAC-SHA512 and the Python requests library?
我有以下代码:
import requests
import hmac
import hashlib
from itertools import count
import time
headers = { 'nonce': '',
'Key' : 'myKey',
'Sign': '',}
payload = { 'command': 'returnCompleteBalances',
'account': 'all'}
secret = 'mySecret'
NONCE_COUNTER = count(int(time.time() * 1000))
headers['nonce'] = next(NONCE_COUNTER)
request = requests.Request(
'POST', 'https://poloniex.com/tradingApi',
params=payload, headers=headers)
signature = hmac.new(secret, request.body, digestmod=hashlib.sha512)
request.headers['Sign'] = signature.hexdigest()
with requests.Session() as session:
response = session.send(request)
以下一行:
signature = hmac.new(secret, request.body, digestmod=hashlib.sha512)
引发此错误:'Request'对象没有属性'body'
答案 0 :(得分:1)
您的源代码有几个问题:
params
,但需要参数data
。.prepare()
方法。nonce
也需要在payload
中指定,而不是在headers
中指定。这应该有效:
import requests
import hmac
import hashlib
from itertools import count
import time
NONCE_COUNTER = count(int(time.time() * 1000))
headers = { 'Key' : 'myKey',
'Sign': '',}
payload = { 'nonce': next(NONCE_COUNTER),
'command': 'returnCompleteBalances',
'account': 'all'}
secret = 'mySecret'
request = requests.Request(
'POST', 'https://poloniex.com/tradingApi',
data=payload, headers=headers).prepare()
signature = hmac.new(secret, request.body, digestmod=hashlib.sha512)
request.headers['Sign'] = signature.hexdigest()
with requests.Session() as session:
response = session.send(request)