首页 > 解决方案 > 烧瓶上的 POST 请求失败

问题描述

我正在尝试从这个页面重现代码,完整的 github 代码在这里

该应用程序在浏览器上运行良好,但我无法从 python 重现 POST 请求。

当我使用浏览器时,我尝试过在有效负载上显示的相同数据

在此处输入图像描述

PEOPLE =  {"fname": "DDoug",
        "lname": "FarDrell"}

url = "http://localhost:5000/api/people"
data = requests.post(url,data=json.dumps(PEOPLE) )

但我收到以下错误:

data.text

'{\n  "detail": "Invalid Content-type (), expected JSON data",\n  "status": 415,\n  "title": "Unsupported Media Type",\n  "type": "about:blank"\n}\n'

我也试过这样:

url = "http://localhost:5000/api/people"
data = requests.post(url,data=json.dumps(PEOPLE) )

但是得到了这个错误:

'{\n  "detail": "Invalid Content-type (application/x-www-form-urlencoded), expected JSON data",\n  "status": 415,\n  "title": "Unsupported Media Type",\n  "type": "about:blank"\n}\n'

标签: pythonapiflask

解决方案


添加Content-Type到您的帖子标题中以指定您要发送 JSON 数据:

requests.post(url,data=json.dumps(PEOPLE), headers={'Content-Type': 'application/json'})

您还可以使用该json参数来实现相同的结果:

requests.post(url, json=json.dumps(PEOPLE))

推荐阅读