首页 > 解决方案 > Python 请求 POST 不包含所有发送的数据

问题描述

我正在尝试通过他们的 REST api 在 PayU 上创建新订单。我正在发送“获取访问令牌”,并且我有正确的答案。然后我发送“创建新订单”,aaaa 并且我收到 103 错误,错误语法。

我正在尝试https://webhook.site/,并意识到为什么语法不好 - 我在列表中没有值。

创建新订单时发送 POST 的代码:

data = {
    "notifyUrl": "https://your.eshop.com/notify",
    "customerIp": "127.0.0.1",
    "merchantPosId": "00000",
    "description": "RTV market",
    "currencyCode": "PLN",
    "totalAmount": "15000",
    "products": [{
                "name": "Wireless mouse",
                "unitPrice": "15000",
                "quantity": "1"}]}

headers = {
"Content-Type": "application/json",
"Authorization": str('Bearer ' + access_token).encode()}

r = requests.post('https://webhook.site/9046f3b6-87c4-4be3-8544-8a3454412a55',
                   data=payload,
                   headers=headers)
return JsonResponse(r.json())

Webhooc 显示我发布的内容:

customerIp=127.0.0.1&notifyUrl=https%3A%2F%2Fyour.eshop.com%2Fnotify&currencyCode=PLN&products=name&products=unitPrice&products=quantity&description=RTV+market&merchantPosId=00000&totalAmount=15000

没有“名称”、“单价”和“数量”的值。PayU 确认这是唯一的问题。

为什么?怎么了?

发送简单的 POST 请求以获取令牌总是成功的。

标签: djangopython-3.xpostpython-requestspayu

解决方案


如果要发送 JSON,请使用以下json参数post()

r = requests.post('https://webhook.site/9046f3b6-87c4-4be3-8544-8a3454412a55',
                   json=payload,  # Use the json argument
                   headers=headers)

否则,数据将作为表单编码数据发送,我猜这不是您想要的,因为您希望发送嵌套products列表。

使用json参数时,内容类型会自动设置为,application/json因此您不必自己设置。

headers = {
    # Content-Type not required
    "Authorization": str('Bearer ' + access_token).encode()
}

有关在此处使用请求发送 JSON 的更多信息


推荐阅读