简体   繁体   English

Coinbase Pro 发布请求 - 格式错误的 JSON

[英]Coinbase Pro post request - Malformed JSON

I am currently working on a piece of software that automates trading with Coinbase Pro.我目前正在开发一款可以使用 Coinbase Pro 自动进行交易的软件。 I am using the request library and have code that works for "GET" requests but fails for "POST"s.我正在使用请求库,并且具有适用于“GET”请求但无法用于“POST”的代码。 I was wondering if someone could help me understand what is going on.我想知道是否有人可以帮助我了解发生了什么。

This is the code I am currently using:这是我目前使用的代码:

import time
import hmac
import hashlib
import base64
import requests
from requests.auth import AuthBase

class CoinbaseExchangeAuth(AuthBase):
  def __init__(self, api_key, secret_key, passphrase):
    self.api_key = api_key
    self.secret_key = secret_key
    self.passphrase = passphrase

  def __call__(self, request):
    timestamp = str(time.time())
    message = timestamp + request.method + request.path_url + (request.body or '')
    message = message.encode('utf-8')
    hmac_key = base64.b64decode(self.secret_key)
    signature = hmac.new(hmac_key, message, hashlib.sha256)
    signature_b64 = base64.b64encode(signature.digest())

    request.headers.update({
        'CB-ACCESS-SIGN': signature_b64,
        'CB-ACCESS-TIMESTAMP': timestamp,
        'CB-ACCESS-KEY': self.api_key,
        'CB-ACCESS-PASSPHRASE': self.passphrase,
        'Content-Type': 'application/json'
    })
    return request

When used with the following:当与以下一起使用时:

api_url = "https://api.pro.coinbase.com/"
auth = CoinbaseExchangeAuth("*****", "*****", "*****")
request = requests.get(api_url + "accounts", auth=auth).json()

It works perfectly.它完美地工作。 But as soon as I try:但是一旦我尝试:

order = {'size': '0.0001', 'price': '100', 'side': 'sell', 'product_id': 'BTC-EUR'}
request = requests.post(api_url + "orders", data=order, auth=auth)
print(request.json())

I get {'message': 'malformed json'} .我收到{'message': 'malformed json'} I figure it has to do with the (request.body or '') but I can't find a fix for it.我认为它与(request.body or '')但我找不到解决方法。

Thank you anyone for help!感谢任何人的帮助!

最后,问题是request = requests.post(api_url + "orders", data=order, auth=auth) - request = requests.post(api_url + "orders", data=json.dumps(order), auth=auth)解决了这个问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM