python - 如何使用 python requests 模块在bitstamp api中发送参数

标签 python python-requests bitcoin

我正在尝试使用 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/

相关文章:

python - 使用请求将文件上传到 python-eve

python - 使用 python 请求获取 ('Connection aborted.' 、 OSError(0, 'Error' ) 错误

events - 什么时候在 bitcoind 上发生 walletnotify 事件

python - 在 pandas 中使用 groupby 用模式替换缺失值时出现 IndexError

python - 为曲线分布图下的阴影区域着色不同的颜色

python - 为什么 Poloniex API 被验证码屏蔽?应为 JSON,但响应为 HTML

Angular4 尝试比较 '[object Object]' 时出错

json - 如何从 API 访问 Kucoin OHLC 数据?

python - 获取包的依赖项而不安装它们

python - 提高代码效率: standard deviation on sliding windows