2013-04-28 76 views
2

我寫,我需要通過API V2連接到MtGox(一個比特幣交易所)交易程序。不過,我不斷收到以下錯誤:問題連接到MtGox API 2與Python

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

HTTP Error 403: Forbidden.

大多數我的劇本是從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腳本將不會運行。你們看到我在做什麼有什麼問題嗎?相當於代碼嗎?

回答

0

此行專門似乎是問題 -

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

爲了澄清,hmac.new()創建一個對象,隨後再調用消化()。摘要返回bytes對象,如

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()) 
0

我相信,你很可能會找到幫助我的一個相關的問題,雖然它涉及WebSocket的API:
Authenticated call to MtGox WebSocket API in Python 3

此外,HTTP 403錯誤似乎表明有某種根本性錯誤的請求。即使你扔在API錯誤的認證信息,你應該得到一條錯誤消息作爲響應,而不是403我最好的猜測是,你使用了錯誤的HTTP方法,以便檢查是否使用了正確的一個(GET/POST)。