2017-10-15 184 views
0

好的,所以我觉得我在这个联盟之外有点小。 我试图以方便自定义HTTP标头是什么在这里要注意:Python3:自定义加密标题URLLIB - KrakenAPI

API-Key = API key 
    API-Sign = Message signature using HMAC-SHA512 of (URI path + SHA256(nonce + POST data)) and base64 decoded secret API key 

https://www.kraken.com/help/api

我想单独制定的urllib如果在所有可能的。

下面是许多尝试得到它编码等所要求的一个:

import os 
    import sys 
    import time 
    import datetime 
    import urllib.request 
    import urllib.parse 
    import json 
    import hashlib 
    import hmac 
    import base64 

    APIKey = 'ThisKey' 
    secret = 'ThisSecret' 

    data = {} 

    data['nonce'] = int(time.time()*1000) 

    data['asset'] = 'ZUSD' 

    uripath = '/0/private/TradeBalance' 

    postdata = urllib.parse.urlencode(data) 

    encoded = (str(data['nonce']) + postdata).encode() 
    message = uripath.encode() + hashlib.sha256(encoded).digest() 

    signature = hmac.new(base64.b64decode(secret), 
        message, hashlib.sha512) 
    sigdigest = base64.b64encode(signature.digest()) 

    #this is purely for checking how things are coming along. 
    print(sigdigest.decode()) 

    headers = { 
    'API-Key': APIKey, 
    'API-Sign': sigdigest.decode() 
    } 

以上可以工作得很好,在那里我现在挣扎适当它让到现场。 这是我最近一次尝试:

myBalance = urllib.urlopen('https://api.kraken.com/0/private/TradeBalance', urllib.parse.urlencode({'asset': 'ZUSD'}).encode("utf-8"), headers) 

任何帮助是极大的赞赏。 谢谢!

+0

信贷,由于顺便说一句,这部分代码是由拉:https://开头的github .com/veox/python3-krakenex 但是由于它使用了请求,我无法在我的机器上运行它。 – Samuel

回答

0

urlopen不支持添加标题,所以你需要创建一个Request对象,并把它传递给urlopen

url = 'https://api.kraken.com/0/private/TradeBalance' 
body = urllib.parse.urlencode({'asset': 'ZUSD'}).encode("utf-8") 
headers = { 
    'API-Key': APIKey, 
    'API-Sign': sigdigest.decode() 
} 

request = urllib.request.Request(url, data=body, headers=headers) 
response = urllib.request.urlopen(request) 
+0

感谢朋友!现在它回来了“{'错误':['EAPI:Invalid key']}”,这让我想到了我编码错误的地方。 – Samuel

+0

得到它的工作,感谢您的帮助! – Samuel