我是Python新手并使用版本3.6.1
我希望我可以使用HMAC-SHA512为poloniex trading api编写Python 3.6.1 Post请求的代码但是出现了这个错误。
我得到的答案大多来自python 2,这不是我想要的。请帮忙。
这是poloniex文档:https://poloniex.com/support/api/
我的python shell首先登录:
{'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
接下来是我的完整代码:
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)
希望任何人都能引导我走向正确的方向。非常感谢。
答案 0 :(得分:0)
我认为你只需要替换:
post_data = urllib.parse.urlencode(req)
通过
post_data = str.encode(urllib.parse.urlencode(req))