Python 来自 API 的密钥编码

Python secret key encoding from API

我一直在尝试使用 Poloniex APIg. I get a key and secret from my account, exactly like this。然后,按照示例,我应该使用以下形式之一:

import poloniex

polo = poloniex.Poloniex('yourApiKeyHere','yourSecretKeyHere123')
# or
polo.APIKey = 'yourApiKeyHere'
polo.Secret = 'yourSecretKeyHere123'

通过使用其中任何一个,我得到了这个错误:

TypeError: key: expected bytes or bytearray, but got 'str'

我试过:

polo.Secret = b'yourSecretKeyHere123'

并得到:

TypeError: Unicode-objects must be encoded before hashing

所以我尝试了:

polo.Secret = 'yourSecretKeyHere123'.encode('utf-8')

我对编码有点不知所云,我也希望 API 只是将我的密钥作为字符串。我错过了什么?

此代码将有效(假设您的 Secret 和 APIKey 都存在,并且 API 不是 IP 或仅限提取限制):

import urllib
import urllib2
import json
import time
import hmac,hashlib


req={}

APIKey = "<my_API_key>"
Secret = "<my_secret>"

command="returnBalances"

req['command'] = command

req['nonce'] = int(time.time()*1000)
post_data = urllib.urlencode(req)

sign = hmac.new(Secret, post_data, hashlib.sha512).hexdigest()
#print sign
headers = {
    'Sign': sign,
    'Key': APIKey
}

ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/tradingApi', post_data, headers))
jsonRet = json.loads(ret.read())

print jsonRet