如何在Flask中获取发布的json? [英] How to get POSTed json in Flask?

查看:189
本文介绍了如何在Flask中获取发布的json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用Flask构建一个简单的API,现在我想读取一些POST JSON。我做的邮递员Chrome扩展后,和JSON我发布的只是 {text:lalala} 。我尝试使用以下方法读取JSON:

pre $ @ 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?

解决方案

您需要将请求内容类型设置为应用程序/ json .json 属性起作用;否则它将是 None 。请参阅 Flask 请求文档
$ b


如果mimetype是 application / json 这将包含解析的JSON数据。否则这将是 None


Flask 0.10添加了 request.get_json()方法,您应该使用该方法而不是 .json 属性。您可以通过设置 force = True 来告诉方法跳过内容类型需求。

注意,如果异常在此时引发(可能导致400个错误的请求响应),那么您的JSON 数据无效。它在某种程度上是畸形的;你可能想用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

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?

解决方案

You need to set the request content type to application/json for the .json property to work; it'll be None otherwise. See the Flask Request documentation:

If the mimetype is application/json this will contain the parsed JSON data. Otherwise this will be None.

Flask 0.10 added the request.get_json() method, and you should use that method instead of the .json property. You can tell the method to skip the content type requirement by setting force=True.

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中获取发布的json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆