自建flask_restfulapireturns使用request模块发布时为NULL

Self-built flask_restful api returns NULL when posted using request module

我最近一直在自学 API,就在我以为我已经开始弄明白的时候,我 运行 遇到了这个问题:

我已经构建了自己的 api,使用 flast_restful:

from flask import Flask, request
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)


class HelloWorld(Resource):
    def get(self):
        return {"hello": "world"}

    def post(self):
        json_str = request.get_json()
        return {"you sent": json_str}


api.add_resource(HelloWorld, "/")

if __name__ == "__main__":
    app.run(debug=True)

我 运行 在控制台中设置它,然后计划使用 python 请求模块在代码中访问它:

import requests

data = {"hello:": "world"}

r = requests.post("http://127.0.0.1:5000", data=data)

print(r.text)

为什么这个 return {"you sent": null},而不是 post 请求中指定的数据? Get请求生效,post请求的响应码为200。

我假设有一些简单的修复方法,但我根本找不到。非常感谢任何帮助!

r = requests.post("http://127.0.0.1:5000", data=data)

这里的问题是 data 没有作为 json 发送;默认为 form-encoded。要正确发送它,您必须在 header 中将内容类型设置为 application/json。你可以这样做:

import json
headers = {'Content-type': 'application/json'}
r = requests.post("http://127.0.0.1:5000", data=json.dumps(data), headers=headers)

或者更简单地说,对于 Requests 版本 2.4.2 及更高版本:

r = requests.post("http://127.0.0.1:5000", json=data)