Flask:通过Response对象发送数据和状态代码 [英] Flask: Sending data and status code through a Response object

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

问题描述

我正在用Flask编写通过API相互交互的微服务.

I am writing Microservices in Flask that interact with each other through API.

在发出POST请求时,我能够通过Response对象返回状态代码.有什么方法可以从此函数作为JSON返回数据?

On making a POST request, I am able to return the status code through the Response object. Is there any way that I can return data from this function as JSON ?

from flask import Flask, Response

@app.route('/login', methods=['POST'])
def login():
   # Set the status code
   response = Response(status=200)

   # How can I return a JSON in my response object as {'username': 'febin'} ?

   return response

推荐答案

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

Simply use jsonify() from flask package. This method takes any serializable data type (for example I have used 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, simply return it at the end of the return as below:

return jsonify(data), 200

这篇关于Flask:通过Response对象发送数据和状态代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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