烧瓶上的POST请求失败

时间:2019-06-10 23:38:32

标签: python api flask

我正在尝试从此page复制代码,完整的github代码是here

该应用程序在浏览器上可以正常工作,但是我无法从python再现POST请求。

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

enter image description here

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'

1 个答案:

答案 0 :(得分:1)

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

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

您还可以使用json参数来获得相同的结果:

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