如何在 Flask 中获取 POSTed JSON? [英] How to get POSTed JSON in Flask?
问题描述
我正在尝试使用 Flask 构建一个简单的 API,我现在想在其中读取一些 POSTed JSON.我使用 Postman Chrome 扩展程序执行 POST,我 POST 的 JSON 只是 {"text":"lalala"}
.我尝试使用以下方法读取 JSON:
I'm trying to build a simple API using Flask, in which I now want to read some POSTed JSON. I do the POST with the Postman Chrome extension, and the JSON I POST is simply {"text":"lalala"}
. I try to read the JSON using the following method:
@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
content = request.json
print content
return uuid
在浏览器上它正确返回了我放在 GET 中的 UUID,但在控制台上,它只打印出 None
(我希望它打印出 {"text":"lalala"}
.有谁知道我如何从 Flask 方法中获取发布的 JSON?
On the browser it correctly returns the UUID I put in the GET, but on the console, it just prints out None
(where I expect it to print out the {"text":"lalala"}
. Does anybody know how I can get the posted JSON from within the Flask method?
推荐答案
首先,.json
属性是委托给 request.get_json()
方法,它记录了您看到 None
的原因这里.
First of all, the .json
attribute is a property that delegates to the request.get_json()
method, which documents why you see None
here.
您需要将 .json
属性和 .get_json()
方法的请求内容类型设置为 application/json
(没有参数),否则将产生 None
.请参阅 Flask Request
文档:
You need to set the request content type to application/json
for the .json
property and .get_json()
method (with no arguments) to work as either will produce None
otherwise. See the Flask Request
documentation:
如果 mimetype 指示 JSON(application/json,请参阅 is_json()
),否则为None
.
This will contain the parsed JSON data if the mimetype indicates JSON (application/json, see
is_json()
), otherwise it will beNone
.
您可以通过将 force=True
关键字参数传递给 request.get_json()
来告诉 request.get_json()
跳过内容类型要求.
You can tell request.get_json()
to skip the content type requirement by passing it the force=True
keyword argument.
请注意,如果此时出现 异常(可能导致 400 Bad Request 响应),则您的 JSON 数据 无效.它在某种程度上是畸形的;您可能需要使用 JSON 验证器进行检查.
Note that if an exception is raised at this point (possibly resulting in a 400 Bad Request response), your JSON data is invalid. It is in some way malformed; you may want to check it with a JSON validator.
这篇关于如何在 Flask 中获取 POSTed JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!