从Flask视图返回JSON响应

时间:2022-10-18 14:11:27

I have a function that analyzes a CSV file with Pandas and produces a dict with summary information. I want to return the results as a response from a Flask view. How do I return a JSON response?

我有一个用熊猫分析CSV文件并生成带有摘要信息的命令的函数。我想返回结果作为Flask视图的响应。如何返回JSON响应?

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

8 个解决方案

#1


411  

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-serializable类型(而不仅仅是dict类型)作为顶层对象。

#2


120  

jsonify serializes the data you pass it to JSON. If you want to serialize the data yourself, do what jsonify does by building a response with status=200 and mimetype='application/json'.

jsonify序列化您传递给JSON的数据。如果您想自己序列化数据,可以像jsonify那样,使用status=200和mimetype='application/json'构建一个响应。

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

#3


83  

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
}

#4


14  

If you want to analyze a file uploaded by the user, the Flask quickstart shows how to get files from users and access them. Get the file from request.files and pass it to the summary function.

如果您想分析用户上传的文件,Flask quickstart将展示如何从用户那里获取文件并访问它们。从请求中获取文件。文件并将其传递给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.

为请求替换“data”键。在HTML表单中输入文件名的文件。

#5


6  

from flask import json
from flask import Response

@app.route('/summary')
def summary():
    data = make_summary()

    response = Response(
        response=json.dumps(data),
        status=200,
        mimetype='application/json'
    )

    return response

#6


4  

Although flask.jsonify is easy to use but I prefer to use a decorator to return json. It helps to returns any json type and is more readable when you have multiple returns in your method. (note that this sample works for 200 responses, I return errors with raising exceptions and Flask.errorhandler)

尽管烧瓶。jsonify很容易使用,但是我更喜欢使用decorator来返回json。它有助于返回任何json类型,并且当方法中有多个返回时,它更具有可读性。(注意,此示例适用于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'

#7


0  

Although an old question, I thought I'll add this if anyone is looking to return an array of JSONs. Flask 0.10 allows you to do this and it's pretty straightforward.

尽管这是一个老问题,但我想如果有人想返回一个JSONs数组,我将添加这个。Flask 0。10允许你这么做,很简单。

@app.route('/get_records')
def get_records():
    list = [
        {
          "rec_create_date": "12 Jun 2016",
          "rec_dietary_info": "nothing",
          "rec_dob": "01 Apr 1988",
          "rec_first_name": "New",
          "rec_last_name": "Guy",
        },
        {
          "rec_create_date": "1 Apr 2016",
          "rec_dietary_info": "Nut allergy",
          "rec_dob": "01 Feb 1988",
          "rec_first_name": "Old",
          "rec_last_name": "Guy",
        },
    ]
    return jsonify(results = list)

#8


-2  

Like said previously jsonify is the best way or you could also use Flask-responses' package at https://github.com/Parkayun/flask-responses

如前所述,jsonify是最好的方法,或者您也可以使用https://github.com/parkayun/flask -response的flask-response包

@app.route("/json")
def hello():
    return json_response(your_dict, status_code=201)

#1


411  

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-serializable类型(而不仅仅是dict类型)作为顶层对象。

#2


120  

jsonify serializes the data you pass it to JSON. If you want to serialize the data yourself, do what jsonify does by building a response with status=200 and mimetype='application/json'.

jsonify序列化您传递给JSON的数据。如果您想自己序列化数据,可以像jsonify那样,使用status=200和mimetype='application/json'构建一个响应。

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

#3


83  

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
}

#4


14  

If you want to analyze a file uploaded by the user, the Flask quickstart shows how to get files from users and access them. Get the file from request.files and pass it to the summary function.

如果您想分析用户上传的文件,Flask quickstart将展示如何从用户那里获取文件并访问它们。从请求中获取文件。文件并将其传递给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.

为请求替换“data”键。在HTML表单中输入文件名的文件。

#5


6  

from flask import json
from flask import Response

@app.route('/summary')
def summary():
    data = make_summary()

    response = Response(
        response=json.dumps(data),
        status=200,
        mimetype='application/json'
    )

    return response

#6


4  

Although flask.jsonify is easy to use but I prefer to use a decorator to return json. It helps to returns any json type and is more readable when you have multiple returns in your method. (note that this sample works for 200 responses, I return errors with raising exceptions and Flask.errorhandler)

尽管烧瓶。jsonify很容易使用,但是我更喜欢使用decorator来返回json。它有助于返回任何json类型,并且当方法中有多个返回时,它更具有可读性。(注意,此示例适用于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'

#7


0  

Although an old question, I thought I'll add this if anyone is looking to return an array of JSONs. Flask 0.10 allows you to do this and it's pretty straightforward.

尽管这是一个老问题,但我想如果有人想返回一个JSONs数组,我将添加这个。Flask 0。10允许你这么做,很简单。

@app.route('/get_records')
def get_records():
    list = [
        {
          "rec_create_date": "12 Jun 2016",
          "rec_dietary_info": "nothing",
          "rec_dob": "01 Apr 1988",
          "rec_first_name": "New",
          "rec_last_name": "Guy",
        },
        {
          "rec_create_date": "1 Apr 2016",
          "rec_dietary_info": "Nut allergy",
          "rec_dob": "01 Feb 1988",
          "rec_first_name": "Old",
          "rec_last_name": "Guy",
        },
    ]
    return jsonify(results = list)

#8


-2  

Like said previously jsonify is the best way or you could also use Flask-responses' package at https://github.com/Parkayun/flask-responses

如前所述,jsonify是最好的方法,或者您也可以使用https://github.com/parkayun/flask -response的flask-response包

@app.route("/json")
def hello():
    return json_response(your_dict, status_code=201)