使用 Flask 响应发送 JSON 和状态代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45412228/
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
Sending JSON and status code with a Flask response
提问by Febin Peter
I know I can set the status code of a response with Response(status=200). How can I return JSON data while setting the status code?
我知道我可以使用Response(status=200). 如何在设置状态码时返回 JSON 数据?
from flask import Flask, Response
@app.route('/login', methods=['POST'])
def login():
response = Response(status=200)
# need to set JSON like {'username': 'febin'}
return response
回答by Nabin
Use flask.jsonify(). This method takes any serializable data type. For example I have used a dictionary datain the following example.
使用flask.jsonify(). 此方法采用任何可序列化的数据类型。例如,我data在以下示例中使用了字典。
from flask import jsonify
@app.route('/login', methods=['POST'])
def login():
data = {'name': 'nabin khadka'}
return jsonify(data)
To return a status code, return a tuple of the response and code:
要返回状态代码,请返回响应和代码的元组:
return jsonify(data), 200
Note that 200 is the default status code, so it's not necessary to specify that code.
请注意,200 是默认状态代码,因此无需指定该代码。
As of Flask 1.1, the return statement will automatically jsonifya dictionary in the first return value. You can return the data directly:
从 Flask 1.1 开始,return 语句会jsonify在第一个返回值中自动生成一个字典。可以直接返回数据:
return data
You can also return it with a status code:
您还可以使用状态代码返回它:
return data, 200
回答by Laurynas Tamulevi?ius
You can append the data to the response like this:
您可以将数据附加到响应中,如下所示:
from flask import Flask, json
@app.route('/login', methods=['POST'])
def login():
data = {"some_key":"some_value"} # Your data in JSON-serializable type
response = app.response_class(response=json.dumps(data),
status=200,
mimetype='application/json')
return response
The response data content type is defined by mimetype parameter.
响应数据内容类型由 mimetype 参数定义。

