I am quite new to Python and using version 3.6.1
I wish i can write code of Python 3.6.1 Post request with HMAC-SHA512 for poloniex trading api but got this error.
Most of answer i get is from python 2 which is not what i want. Please help.
Here is poloniex documentation: https://poloniex.com/support/api/
My python shell log first:
{'command': 'returnBalances', 'nonce': 1492523610}
command=returnBalances&nonce=1492523610
Traceback (most recent call last):
File "C:/Users/draft/Desktop/test3.py", line 21, in <module>
signing = hmac.new(secret, post_data, hashlib.sha512).hexdigest()
File "C:\Users\draft\AppData\Local\Programs\Python\Python36-32\lib\hmac.py", line 144, in new
return HMAC(key, msg, digestmod)
File "C:\Users\draft\AppData\Local\Programs\Python\Python36-32\lib\hmac.py", line 84, in __init__
self.update(msg)
File "C:\Users\draft\AppData\Local\Programs\Python\Python36-32\lib\hmac.py", line 93, in update
self.inner.update(msg)
TypeError: Unicode-objects must be encoded before hashing
Next is my full code:
import urllib.request
import urllib.parse
import hmac
import hashlib
import time
import json
t = int(time.time())
secret = b'<secret>'
headers = { 'Key' : '<api key>',
'Sign': ''}
url = 'https://poloniex.com/tradingApi'
req={}
req['command'] = 'returnBalances'
req['nonce'] = int(time.time())
#print (req)
post_data = urllib.parse.urlencode(req)
#print (post_data)
signing = hmac.new(secret, post_data, hashlib.sha512).hexdigest()
#print (signing)
headers['Sign'] = signing
ret = urllib.request.Request(url, data, headers)
#print (ret)
ret = urllib.request.urlopen(ret)
a = json.loads(ret.read())
#print (a)
Hope anybody can lead me to the correct direction. Thanks a lot.