【问题标题】:Problems Connecting to MtGox API 2 with Python使用 Python 连接到 MtGox API 2 的问题
【发布时间】:2013-04-28 15:44:03
【问题描述】:

我正在编写一个交易程序,我需要通过 API v2 连接到 MtGox(比特币交易所)。但我不断收到以下错误:

网址:1https://data.mtgox.com/api/2/BTCUSD/money/bitcoin/address

HTTP 错误 403:禁止。

我的大部分脚本都是来自here 的直接副本(即粘贴链接)。我只需要更改它以使用 Python 3.3。

我怀疑这与我使用 base64.b64encode 的脚本部分有关。 In my code,我必须将我的字符串编码为 utf-8 才能使用 base64.b64encode:

                url = self.__url_parts + '2/' + path
                api2postdatatohash = (path + chr(0) + post_data).encode('utf-8')          #new way to hash for API 2, includes path + NUL
                ahmac = base64.b64encode(str(hmac.new(base64.b64decode(self.secret),api2postdatatohash,hashlib.sha512).digest()).encode('utf-8'))
            
                # Create header for auth-requiring operations
                header = {
                     "User-Agent": 'Arbitrater',
                     "Rest-Key": self.key,
                     "Rest-Sign": ahmac
                }

但是,对于其他人的脚本,他没有:

                url = self.__url_parts + '2/' + path
                api2postdatatohash = path + chr(0) + post_data          #new way to hash for API 2, includes path + NUL
                ahmac = base64.b64encode(str(hmac.new(base64.b64decode(self.secret),api2postdatatohash,hashlib.sha512).digest()))
           
                # Create header for auth-requiring operations
                header = {
                     "User-Agent": 'genBTC-bot',
                      "Rest-Key": self.key,
                     "Rest-Sign": ahmac
                }

我想知道额外的编码是否导致我的标头凭据不正确。我认为这是另一个 Python 2 v. Python 3 问题。我不知道其他人如何在不更改为 utf-8 的情况下逃脱,因为如果您尝试将字符串传递给 b64encode 或 hmac,脚本将不会运行。你们看到我在做什么有什么问题吗? out code 是不是等价的?

【问题讨论】:

    标签: api python-3.x mtgox


    【解决方案1】:

    这一行似乎是问题所在 -

    ahmac = base64.b64encode(str(hmac.new(base64.b64decode(self.secret),api2postdatatohash,hashlib.sha512).digest()).encode('utf-8'))
    

    为了澄清,hmac.new() 创建了一个对象,然后调用 digest()。摘要返回一个字节对象,例如

    b.digest()
    
    b'\x92b\x129\xdf\t\xbaPPZ\x00.\x96\xf8%\xaa'
    

    现在,当您对此调用 str 时,它会变成 b'\\x92b\\x129\\xdf\\t\\xbaPPZ\\x00.\\x96\\xf8%\\xaa'

    那么,看看那里会发生什么?字节指示符现在是字符串本身的一部分,然后您将其称为encode()

    str(b.digest()).encode("utf-8")
    b"b'\\x92b\\x129\\xdf\\t\\xbaPPZ\\x00.\\x96\\xf8%\\xaa'"
    

    为了解决这个问题,因为无论如何都不需要将字节转换为字符串再转换为字节(除了有问题),我相信这会起作用 -

    ahmac = base64.b64encode(hmac.new(base64.b64decode(self.secret),api2postdatatohash,hashlib.sha512).digest())
    

    【讨论】:

      【解决方案2】:

      我相信您可能会在我的一个相关问题中找到帮助,尽管它涉及 WebSocket API:
      Authenticated call to MtGox WebSocket API in Python 3

      此外,HTTP 403 错误似乎表明请求存在根本性错误。即使您在 API 中输入了错误的身份验证信息,您也应该收到一条错误消息作为响应,而不是 403。我最好的猜测是您使用了错误的 HTTP 方法,因此请检查您是否使用了适当的方法(GET/发布)。

      【讨论】:

        猜你喜欢
        • 2017-06-16
        • 1970-01-01
        • 1970-01-01
        • 2020-01-24
        • 1970-01-01
        • 2022-12-06
        • 1970-01-01
        • 2011-09-01
        • 1970-01-01
        相关资源
        最近更新 更多