将PHP代码转换为Python(Rest-API连接)

4
我正在学习Python,作为练习,我尝试编写一个程序在比特币市场上进行交易:https://bitcurex.com。这是一个API参考:https://bitcurex.com/reading-room/API。有一个PHP客户端示例,所以我试图将其翻译成Python,于是我得到了以下代码:
import math
import time
import simplejson
import urllib
import urllib2
import hmac,hashlib

def microtime():
    return '%f %d' % math.modf(time.time())

def query( path, key, secret, data={} ):
    mt = microtime().split()
    nonce = mt[1] + mt[0][2:]
    data['nonce'] = nonce

    post_data = urllib.urlencode( data )

    sign = hmac.new( secret.decode('base64'), post_data, hashlib.sha512 ).digest()

    headers = {'Rest-Key' : key,
               'Rest-Sign': sign.encode('base64').strip(),
               'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
               'Content-type': 'application/x-www-form-urlencoded'}
    print headers

    url = 'https://bitcurex.com/api/0/' + path

    req = urllib2.Request( url, post_data, headers )
    response = urllib2.urlopen(req)

    return simplejson.loads(response.read())

print query('getFunds', '29a28e8fe234537056a8b256c0df50413f50da9c49ca61991ea8b8f108a88e09',  'y2NDxKGa/xvhtXrDP+3oscbBUFSac9+T8jzu2nRmt0vBdHbbl8NRqdmxKFr2IwwY5LAskTQZGyy2XONaNN6Jrg==')

这些API密钥可用 - 您只能使用它们进行getFunds查询。

它一直返回错误“必须登录”。我尝试通过Fiddler Proxy Debugger查看该请求,以下是该尝试的标题:

POST /api/0/getFunds HTTP/1.1
Accept-Encoding: identity
Rest-Sign: Dd1WBn2T5SYTbqMMohOxr46IaLDrkelgH7AgkrrB0mT0PxKfv15vSJ3b6xNdc5PO2Yz9cDpu0u/H
WIc7bH56sQ==: 
Content-Length: 22
Rest-Key: 29a28e8fe234537056a8b256c0df50413f50da9c49ca61991ea8b8f108a88e09
Connection: close
User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)
Host: bitcurex.com
Content-Type: application/x-www-form-urlencoded

Fiddler向我显示了一个错误:
Incorrectly formed request headers.
Missing colon in header #3, WIc7bH56sQ==

有什么想法吗?看起来我的Rest-Sign太长了或者类似于这样的问题。我认为我的代码应该与PHP示例完全相同。我做错了什么?

1个回答

2

这一行很可疑:

'Rest-Sign': sign.encode('base64').strip()

您真的希望标题的值包含文字 '\n' 吗?这是 encode('base64') 返回的结果 --- 在您的示例中,返回的字符串如下:

'Dd1WBn2T5SYTbqMMohOxr46IaLDrkelgH7AgkrrB0mT0PxKfv15vSJ3b6xNdc5PO2Yz9cDpu0u/H\nWIc7bH56sQ=='

请注意中间的\n。我不确定,但可能删除所有\n符号会给您所需的结果。

对我也起作用了,但每次我都得到403响应。我使用了自己的密钥/秘密值,但仍然无法登录。 - meso_2600

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接