Python Flask 请求和 application/json 内容类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14112336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Flask request and application/json content type
提问by danielrvt
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.jsonis None.
但是,这仅在请求的内容类型设置为 时才有效application/json,否则 dictrequest.json为 None。
I know that request.datahas 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? All I want is to always have access to a valid request.jsondict, even if the client forgets to set the application content-type to json.
有没有办法假设每个传入请求的内容类型都是application/json?我想要的只是始终可以访问有效的request.jsondict,即使客户端忘记将应用程序内容类型设置为 json。
采纳答案by Martijn Pieters
Use request.get_json()and set forceto 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/jsonbut this can be overridden by the forceparameter.Parameters:
- force– if set to Truethe mimetype is ignored.
默认情况下,如果 mimetype 是,此函数将仅加载 json 数据,
application/json但这可以被force参数覆盖。参数:
- 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))
回答by josebama
the requestobject already has a method get_jsonwhich can give you the json regardless of the content-type if you execute it with force=Trueso your code would be something like the following:
该request对象已经有一个方法get_json,如果您执行它,则无论内容类型如何,该方法都可以为您提供 json,force=True因此您的代码将类似于以下内容:
@menus.route('/', methods=["PUT", "POST"])
def new():
return jsonify(request.get_json(force=True))
in fact, the flask documentation says that request.get_jsonshould 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

