【发布时间】:2013-09-01 10:23:33
【问题描述】:
我正在尝试使用 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 中对字节和字符串编码和解码所做的更改有关。
提前非常感谢!
【问题讨论】:
标签: python json websocket mtgox