【问题标题】:POST request fails on flask [duplicate]烧瓶上的POST请求失败[重复]
【发布时间】:2019-10-25 08:17:50
【问题描述】:

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

该应用程序在浏览器上运行良好,但我无法重现来自 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'

【问题讨论】:

    标签: python api flask


    【解决方案1】:

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

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

    你也可以使用json参数来达到同样的效果:

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

    【讨论】:

    • 有些例子没有,你怎么知道有必要?
    • 默认请求头是None,所以不会被读取为JSON。您还可以(作为速记)使用json= 参数来避免headers={...。我将更新我的答案以包含此内容。
    猜你喜欢
    • 2020-11-24
    • 1970-01-01
    • 1970-01-01
    • 2014-04-11
    • 1970-01-01
    • 2014-06-29
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    相关资源
    最近更新 更多