Python的请求,没有属性“体”
问题描述:
我试图运行一个类似于在这个问题上的代码:How do I sign a POST request using HMAC-SHA512 and the Python requests library?Python的请求,没有属性“体”
我有以下代码:
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)
抛出这个错误:'请求' 对象有没有属性 '身体'
答
你的源代码有几个问题:
- 因为你不能使用参数
params
POST方法,但你需要的参数data
。 - 如前所述,您需要使用
.prepare()
方法。 - 参数
nonce
还需要在中指定,而不是在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)
尝试:request.content – Gui
,我收到了类似的错误:“请求”对象有没有属性“内容” –
尝试request.text –