You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用requests库发送PUT请求时键无法正常传递,Postman可正常运行

问题排查与解决

核心问题分析

你的代码存在两个关键错误,导致请求格式和Postman发送的不一致:

  • Content-Type位置错误:你把Content-Type: application/json放到了params(URL参数)里,这是HTTP请求头的内容,应该放在headers中。
  • 请求数据格式不匹配:使用data参数传递字典时,requests会默认将数据编码为application/x-www-form-urlencoded格式,而非后端期望的JSON格式,这就导致后端无法正确解析key 3所在的嵌套结构。

修正后的代码

import requests

jsn = {'key 1': 'item 01', 'key 2': 'item 02', 'key 3': 'item 03'}
headers = {
    'Authorization-Token': token,
    'User': user,
    'App': 'API',
    'Content-Type': 'application/json'  # 移到headers里
}
url = url
data = {'pedido': jsn}

# 使用json参数传递数据,requests会自动序列化并设置正确的Content-Type
request_put = requests.put(url, headers=headers, json=data)
print(request_put.text)

补充说明

如果不想用json参数,也可以手动将数据序列化为JSON字符串,再用data传递,但需要确保headers里的Content-Type正确:

import json

# ... 其他代码不变
request_put = requests.put(url, headers=headers, data=json.dumps(data))

内容的提问来源于stack exchange,提问作者matheusppedroso

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 12:55:12