【问题标题】:How to format a JSON object to send it through header in python?如何格式化 JSON 对象以通过 python 中的标头发送它?
【发布时间】:2019-09-19 02:44:54
【问题描述】:

我希望与之交互的 API 要求提供“密钥”、“随机数”和“签名”,这是它必须如何构建的:

“签名是通过在 nonce + HTTP 方法 + requestPath + JSON 有效负载(连接字符串中没有'+'符号)的串联上使用 Bitso API Secret 创建一个 SHA256 HMAC 并对输出进行十六进制编码来生成的。nonce value 应该与 Authorization 标头中的 nonce 字段相同。当然,requestPath 和 JSON 有效负载必须与请求中使用的完全相同。"

问题是当我尝试发送 json 有效负载时。如果我将 json 有效负载作为 dict 发送,程序会说它不能与字符串连接,当我将它作为字符串发送时,服务器响应说 nonce 无效。

我应该如何构建 json 负载?

这是我将有效负载作为字符串发送的代码:

import time
import hmac
import hashlib
import requests

bitso_key = "xxxxxxxxxx"
bitso_secret = "xxxxxxxxxxxxxxxxxxxxxxxx"
nonce =  str(int(round(time.time() * 1000)))
http_method = "POST"
request_path = "/v3/orders/"
json_payload = """{'book':'xrp_mxn','side':'sell','type':'market','major':'0.5'}"""

print(json_payload)

# Create signature
message = nonce+http_method+request_path+json_payload
print(message)
signature = hmac.new(bitso_secret.encode('utf-8'),message.encode('utf-8'),hashlib.sha256).hexdigest()
# Build the auth header
auth_header = 'Bitso %s:%s:%s' % (bitso_key, nonce, signature)

# Send request
response = requests.get("https://api.bitso.com/v3/orders/", headers={"Authorization": auth_header})

print (response.content)

回复如下:

b'{"success":false,"error":{"code":"0201","message":"Nonce o credenciales inv\\u00e1lidas"}}'

如果我将其作为字典发送:

json_payload = {'book':'xrp_mxn','side':'sell','type':'market','major':'0.5'}

回复如下:

message = nonce+http_method+request_path+json_payload
TypeError: can only concatenate str (not "dict") to str

这里是 api 的文档页面:https://bitso.com/api_info#place-an-order

【问题讨论】:

  • 这是 response 还是 local TypeError?无论如何,显示的原始 JSON 字符串是 not JSON,因此预计会失败(JSON 键 always 用双引号括起来;其他任何内容都是无效的 JSON)。
  • 使用正确的 JSON 编码 生成正确的 JSON(而不是显示的非 JSON 字符串)。然后将此作为文本用于签名和请求正文。例如:json_text = json.dumps(object_to_send..).
  • @user2864740 TypeError 是由于 dict + 字符串连接导致的本地错误。如果它不是 JSON,那么 JSON 应该是什么样子?
  • json.org - 解释 JSON 语法。
  • 谢谢你,我会检查那个功能,它似乎是我要找的。​​span>

标签: python json post


【解决方案1】:

您不能将字符串与dict 连接,但您可以使用json 库将dict 转换为json 字符串:

import json
import time

nonce = str(int(round(time.time() * 1000)))
http_method = "POST"
request_path = "/v3/orders/"

payload = {'book': 'xrp_mxn', 'side': 'sell', 'type': 'market', 'major': '0.5'}
json_payload = json.dumps(payload)

message = nonce + http_method + request_path + json_payload
print(message)

你得到:

1568403950209POST/v3/orders/{"major": "0.5", "type": "market", "book": "xrp_mxn", "side": "sell"}

【讨论】:

  • 我已经完成了,服务器的响应还是一样:'nonce o credenciales invalidas''。让我检查一下随机数、凭据和函数转储。
【解决方案2】:

正如 user2864740 和 Laurent LAPORTE 所评论的,代码的问题在于将字符串编码为 JSON 格式,而且我使用的代码来自 API 官方文档中的旧版本,因此我检查了较新的和格式将字典转换成 JSON 并完成。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-05
    • 1970-01-01
    • 2019-09-17
    • 1970-01-01
    • 2014-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多