我正在尝试为 kraken 编写一个不错的身份验证助手。我希望它尽可能自动化,所以它需要:
time.time()*1000
在 POST 正文中添加一个 nonce ( )- 计算 POST 正文上的签名
- 将签名放入标题中
我根据这个答案编写了明显的代码:
class KrakenAuth(AuthBase):
"""a requests-module-compatible auth module for kraken.com"""
def __init__(self, key, secret):
self.api_key = key
self.secret_key = secret
def __call__(self, request):
#print("Auth got a %r" % type(request))
nonce = int(1000*time.time())
request.data = getattr(request, 'data', {})
request.data['nonce'] = nonce
request.prepare()
message = request.path_url + hashlib.sha256(str(nonce) + request.body).digest()
hmac_key = base64.b64decode(self.secret_key)
signature = hmac.new(hmac_key, message, hashlib.sha512).digest()
signature = base64.b64encode(signature)
request.headers.update({
'API-Key': self.api_key,
'API-Sign': signature
})
return request
我正在调用它(来自另一个对象的包装器方法),例如:
def _request(self, method, url, **kwargs):
if not self._auth:
self._auth = KrakenAuth(key, secret)
if 'auth' not in kwargs:
kwargs['auth'] = self._auth
return self._session.request(method, URL + url, **kwargs)
...但它不起作用。注释掉的print()
语句表明它得到的是一个PreparedRequest
对象而不是一个Request
对象,因此调用request.prepare()
是一个调用PreparedRequest.prepare
没有什么用处,因为没有request.data
,因为它已经被转换为一个body
属性。