Python请求,没有属性'body'

时间:2017-11-11 05:00:41

标签: python rest http post python-requests

我正在尝试运行类似于此问题中的代码: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'

1 个答案:

答案 0 :(得分:1)

您的源代码有几个问题:

  1. 对于POST方法,您不能使用参数params,但需要参数data
  2. 如前所述,您需要.prepare()方法。
  3. 参数nonce也需要在payload中指定,而不是在headers中指定。
  4. 这应该有效:

    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)