问题描述
我知道我可以使用 Response(status=200)
设置响应的状态代码.设置状态码时如何返回JSON数据?
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?
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
推荐答案
使用 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
请注意,200 是默认状态代码,因此无需指定该代码.
Note that 200 is the default status code, so it's not necessary to specify that code.
从 Flask 1.1 开始,return 语句会自动在第一个返回值中jsonify
一个字典.可以直接返回数据:
As of Flask 1.1, the return statement will automatically jsonify
a dictionary in the first return value. You can return the data directly:
return data
你也可以返回一个状态码:
You can also return it with a status code:
return data, 200
这篇关于使用 Flask 响应发送 JSON 和状态代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!