[英]Flask request and application/json content type
I have a flask app with the following view: 我有一个带有以下视图的烧瓶应用程序:
@menus.route('/', methods=["PUT", "POST"])
def new():
return jsonify(request.json)
However, this only works if the request's content type is set to application/json
, otherwise the dict request.json
is None. 但是,这仅在请求的内容类型设置为application/json
,否则dict request.json
为None。
I know that request.data
has the request body as a string, but I don't want to be parsing it to a dict everytime a client forgets to set the request's content-type. 我知道request.data
将请求主体作为字符串,但我不希望每次客户端忘记设置请求的内容类型时将其解析为dict。
Is there a way to assume that every incoming request's content-type is application/json
? 有没有办法假设每个传入请求的内容类型是application/json
? All I want is to always have access to a valid request.json
dict, even if the client forgets to set the application content-type to json. 我想要的是始终可以访问有效的request.json
dict,即使客户端忘记将应用程序内容类型设置为json。
Use request.get_json()
and set force
to True
: 使用request.get_json()
并将force
设置为True
:
@menus.route('/', methods=["PUT", "POST"])
def new():
return jsonify(request.get_json(force=True))
From the documentation: 从文档:
By default this function will only load the json data if the mimetype is
application/json
but this can be overridden by the force parameter. 默认情况下,如果mimetype是application/json
此函数将仅加载json数据,但这可以被force参数覆盖。Parameters: 参数:
- force – if set to True the mimetype is ignored. force - 如果设置为True ,则忽略mimetype。
For older Flask versions, < 0.10, if you want to be forgiving and allow for JSON, always, you can do the decode yourself, explicitly: 对于较旧的Flask版本,<0.10,如果您想要宽容并允许使用JSON,您可以自己进行解码:
from flask import json
@menus.route('/', methods=["PUT", "POST"])
def new():
return jsonify(json.loads(request.data))
the request
object already has a method get_json
which can give you the json regardless of the content-type if you execute it with force=True
so your code would be something like the following: request
对象已经有一个方法get_json
,如果你用force=True
执行它,它可以为你提供json而不管内容类型如何,所以你的代码将如下所示:
@menus.route('/', methods=["PUT", "POST"])
def new():
return jsonify(request.get_json(force=True))
in fact, the flask documentation says that request.get_json
should be used instead of request.json
: http://flask.pocoo.org/docs/api/?highlight=json#flask.Request.json 事实上,烧瓶文件说, request.get_json
应该用来代替request.json
: http://flask.pocoo.org/docs/api/?highlight=json#flask.Request.json
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.