[英]Authenticated call to MtGox WebSocket API in Python 3
我正在尝试使用MtGox.com WebSocket API进行身份验证,并在很长一段时间后设法完成了JSON数据所需的“调用”属性。 但是,我意识到我正在使用Python 2运行我的代码示例,并且最终要在其中实现API的应用程序是用Python 3编写的。当我试图使其在Python 3中运行时,我遇到了两个问题经过数次长时间尝试后仍无法解决。
我也尝试了2to3
,但似乎没有针对这些问题的内置修复程序。
可在以下位置找到经过身份验证的API调用的API规范: https : //en.bitcoin.it/wiki/MtGox/API/Streaming#Authenticated_commands
这是我用来生成JSON调用的有效Python 2脚本,然后通过为Chrome找到的WebSocket控制台扩展运行该脚本。
import hashlib
import time
import hmac
import json
import base64
import binascii
apikey = ""
apisecret = ""
def _nonce():
"""produce a unique nonce that is guaranteed to be ever increasing"""
microtime = int(time.time() * 1E6)
return microtime
def _reqid(nonce):
return hashlib.md5(str(nonce)).hexdigest()
def send_signed_call(api_endpoint, params):
nonce = _nonce()
reqid = _reqid(nonce)
call = json.dumps({
"id" : reqid,
"nonce" : nonce,
"call" : api_endpoint,
"params" : params,
})
sign = hmac.new(base64.b64decode(apisecret), call, hashlib.sha512).digest()
signedcall = apikey.replace("-", "").decode("hex") + sign + call
return json.dumps({
"op" : "call",
"call" : base64.b64encode(signedcall),
"id" : reqid,
"context" : "mtgox.com"
})
msg = send_signed_call("private/info", {})
print(msg)
我遇到的一些错误与不再存在的String.decode(“ hex”)有关,我还有其他一些错误,但是不幸的是,由于尝试了许多不同的方法,我没有跟踪所有错误。 我还查看了其他语言中具有相同功能的代码示例,但找不到与Python 3问题有关的任何线索。 似乎与Python 3中对字节和字符串的编码和解码所做的更改有关。
在此先多谢!
终于解决了!
这是send_signed_call
函数的工作版本,请欣赏:
def send_signed_call(api_endpoint, params):
nonce = _nonce()
reqid = _reqid(nonce)
call = json.dumps({
"id" : reqid,
"nonce" : nonce,
"call" : api_endpoint,
"params" : params,
})
callByte = bytes(call, "utf-8")
sign = hmac.new(base64.b64decode(api_secret), callByte, hashlib.sha512).digest()
skey = bytes.fromhex(api_key.replace("-",""))
signedcall = skey + sign + callByte
return json.dumps({
"op" : "call",
"call" : base64.b64encode(signedcall).decode("utf-8"),
"id" : reqid,
"context" : "mtgox.com"
})
你们不知道我现在熊猫有多幸福!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.