我正在尝试使用 Bitstamp api,并且能够成功调用任何只需要 key 、签名和随机数参数的东西。然而,当我尝试转账或订购时,这需要额外的参数,如地址或价格和金额,我的请求似乎变得困惑。我对编程、API 和请求很陌生。
def sell(self, product):
nonce = self.get_nonce() #an integer time.time()*10000
btc = self.get_btc_bal() #float
price = self.get_btcusd_bid() #float
amount = float(str(btc)[:5])
message = str(nonce) + self.customer_id + self.api_key
signature = hmac.new(self.api_secret, msg=message, digestmod=hashlib.sha256).hexdigest().upper()
r = requests.post(self.url + 'sell/btcusd/', params={'key':self.api_key, 'signature':signature, 'nonce': nonce, 'amount': amount, 'price':price})
r = r.json()
print(r)
print('open sell order in Bitstamp for %s BTC at %s USD'%(amount,price))
我的确切问题是如何正确格式化/组织/编码参数。当我像这样发送它时,它会返回
{"status": "error", "reason": "Missing key, signature and nonce parameters.", "code": "API0000"}
如果我不使用params=
它会返回
{"status": "error", "reason": "Invalid nonce", "code": "API0004"}
我不相信随机数的原因,因为我对所有请求使用完全相同的 get_nonce() 方法。我希望有人能看出我错在哪里,谢谢
最佳答案
您应该使用data =而不是params:
requests.post(self.url + 'sell/btcusd/', data={'key':self.api_key, 'signature':signature, 'nonce': nonce, 'amount': amount, 'price':price})
当您使用data =时,数据将在请求正文中发送:
In [17]: req = requests.post("https://httpbin.org/post", data=data)
In [18]: req.request.body
Out[18]: 'foo=bar'
In [19]: req.json()
Out[19]:
{u'args': {},
u'data': u'',
u'files': {},
u'form': {u'foo': u'bar'},
u'headers': {u'Accept': u'*/*',
u'Accept-Encoding': u'gzip, deflate',
u'Content-Length': u'7',
u'Content-Type': u'application/x-www-form-urlencoded',
u'Host': u'httpbin.org',
u'User-Agent': u'python-requests/2.10.0'},
u'json': None,
u'origin': u'178.167.254.183',
u'url': u'https://httpbin.org/post'}
使用 params 创建一个在 url 中包含键/值对的查询字符串,并且请求没有正文:
In [21]: req = requests.post("https://httpbin.org/post", params=data)
In [22]: req.request.body
In [23]: req.json()
Out[23]:
{u'args': {u'foo': u'bar'},
u'data': u'',
u'files': {},
u'form': {},
u'headers': {u'Accept': u'*/*',
u'Accept-Encoding': u'gzip, deflate',
u'Content-Length': u'0',
u'Host': u'httpbin.org',
u'User-Agent': u'python-requests/2.10.0'},
u'json': None,
u'origin': u'178.167.254.183',
u'url': u'https://httpbin.org/post?foo=bar'}
In [24]: req.url
Out[24]: u'https://httpbin.org/post?foo=bar'
关于python - 如何使用 python requests 模块在bitstamp api中发送参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39427756/