从Flask视图返回JSON响应

本文翻译自:Return JSON response from Flask view

I have a function that analyzes a CSV file with Pandas and produces a dict with summary information. 我有一个函数,可使用Pandas分析CSV文件并生成带有摘要信息的字典。 I want to return the results as a response from a Flask view. 我想从Flask视图返回结果作为响应。 How do I return a JSON response? 如何返回JSON响应?

@app.route("/summary")
def summary():
    d = make_summary()
    # send it back as json

#1楼

参考:https://stackoom.com/question/st6S/从Flask视图返回JSON响应


#2楼

Pass keyword arguments to flask.jsonify and they will be output as a JSON object. 将关键字参数传递给flask.jsonify ,它们将作为JSON对象输出。

@app.route('/_get_current_user')
def get_current_user():
    return jsonify(
        username=g.user.username,
        email=g.user.email,
        id=g.user.id
    )
{
    "username": "admin",
    "email": "admin@localhost",
    "id": 42
}

If you already have a dict, you can pass it directly as jsonify(d) . 如果您已有字典,则可以将其作为jsonify(d)直接传递。


#3楼

Pass the summary data to the jsonify function, which returns a JSON response. 将摘要数据传递给jsonify函数,该函数返回JSON响应。

from flask import jsonify

@app.route('/summary')
def summary():
    d = make_summary()
    return jsonify(d)

As of Flask 0.11, you can pass any JSON-serializable type, not just dict, as the top level object. 从Flask 0.11开始,您可以将任何JSON可序列化类型(不仅是dict)传递为顶级对象。


#4楼

If you want to analyze a file uploaded by the user, the Flask quickstart shows how to get files from users and access them. 如果要分析用户上传的文件,则Flask 快速入门会显示如何从用户获取文件并进行访问。 Get the file from request.files and pass it to the summary function. request.files获取文件,并将其传递给summary函数。

from flask import request, jsonify
from werkzeug import secure_filename

@app.route('/summary', methods=['GET', 'POST'])
def summary():
    if request.method == 'POST':
        csv = request.files['data']
        return jsonify(
            summary=make_summary(csv),
            csv_name=secure_filename(csv.filename)
        )

    return render_template('submit_data.html')

Replace the 'data' key for request.files with the name of the file input in your HTML form. request.files'data'键替换为HTML表单中输入的文件名。


#5楼

jsonify serializes the data you pass it to JSON. jsonify序列化您传递给JSON的数据。 If you want to serialize the data yourself, do what jsonify does by building a response with status=200 and mimetype='application/json' . 如果要自己序列化数据,请通过构建一个status=200mimetype='application/json'的响应来执行jsonify操作。

from flask import json

@app.route('/summary')
def summary():
    data = make_summary()
    response = app.response_class(
        response=json.dumps(data),
        status=200,
        mimetype='application/json'
    )
    return response

#6楼

Although flask.jsonify is easy to use but I prefer to use a decorator to return json. 虽然flask.jsonify易于使用,但我更喜欢使用装饰器返回json。 It helps to returns any json type and is more readable when you have multiple returns in your method. 它有助于返回任何json类型,并且当您的方法中有多个返回值时,它更具可读性。 (note that this sample works for 200 responses, I return errors with raising exceptions and Flask.errorhandler ) (请注意,此示例适用于200个响应,我通过引发异常和Flask.errorhandler返回错误)

def return_json(f):
    @functools.wraps(f)
    def inner(*a, **k):
        return json.dumps(f(*a, **k))
    return inner


@app.route('/test/<arg>')
@return_json
def test(arg):
    if arg == 'list':
        return [1, 2, 3]
    elif arg == 'dict':
        return {'a': 1, 'b': 2}
    elif arg == 'bool':
        return True
    return 'non of them'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值