0

I am trying to run a code similar to the one in this question: How do I sign a POST request using HMAC-SHA512 and the Python requests library?

I have the following code:

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)

The following line :

signature = hmac.new(secret, request.body, digestmod=hashlib.sha512)

Throws this error: 'Request' object has no attribute 'body'

Mustard Tiger
  • 3,520
  • 8
  • 43
  • 68

1 Answers1

2

Your source code has several problems:

  1. For the POST method you can't use the argument params, but you need the argument data.
  2. As mentioned before, you need the .prepare() method.
  3. The parameter nonce needs to be specified also in payload, not in headers.

This should work:

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)
xhancar
  • 687
  • 1
  • 6
  • 14