使用Flask响应发送JSON和状态代码 [英] Sending JSON and status code with a Flask response

查看:191
本文介绍了使用Flask响应发送JSON和状态代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以使用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

推荐答案

使用 .此方法采用任何可序列化的数据类型.例如,在以下示例中,我使用了字典data.

Use flask.jsonify(). This method takes any serializable data type. For example I have used a dictionary data in the following example.

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

您还可以返回状态码:

return data, 200

这篇关于使用Flask响应发送JSON和状态代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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