Return JSON response from Flask view

前端 未结 15 2614
时光取名叫无心
时光取名叫无心 2020-11-21 05:11

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 r

相关标签:
15条回答
  • 2020-11-21 05:56
    from flask import jsonify
    app = Flask(__name__)
    @app.route('/summary')
    def summary():
    
       d = make_summary()
       return jsonify(d)
    
    0 讨论(0)
  • 2020-11-21 06:00

    Flask 1.1.x

    now Flask support request return with json directly, jsonify not required anymore

    @app.route("/")
    def index():
        return {
            "api_stuff": "values",
        }
    

    is equivalent to

    @app.route("/")
    def index():
        return jsonify({
            "api_stuff": "values",
        })
    

    for more information read here https://medium.com/octopus-wealth/returning-json-from-flask-cf4ce6fe9aeb and https://github.com/pallets/flask/pull/3111

    0 讨论(0)
  • 2020-11-21 06:03

    Prior to Flask 0.11, jsonfiy would not allow returning an array directly. Instead, pass the list as a keyword argument.

    @app.route('/get_records')
    def get_records():
        results = [
            {
              "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)
    
    0 讨论(0)
  • 2020-11-21 06:03

    """ Using Flask Class-base View """

    from flask import Flask, request, jsonify
    
    from flask.views import MethodView
    
    app = Flask(**__name__**)
    
    app.add_url_rule('/summary/', view_func=Summary.as_view('summary'))
    
    class Summary(MethodView):
    
        def __init__(self):
            self.response = dict()
    
        def get(self):
            self.response['summary'] = make_summary()  # make_summary is a method to calculate the summary.
            return jsonify(self.response)
    
    0 讨论(0)
  • 2020-11-21 06:04

    I use a decorator to return the result of jsonfiy. I think it is more readable when a view has multiple returns. This does not support returning a tuple like content, status, but I handle returning error statuses with app.errorhandler instead.

    import functools
    from flask import jsonify
    
    def return_json(f):
        @functools.wraps(f)
        def inner(**kwargs):
            return jsonify(f(**kwargs))
    
        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 'none of them'
    
    0 讨论(0)
  • 2020-11-21 06:06

    To return a JSON response and set a status code you can use make_response:

    from flask import jsonify, make_response
    
    @app.route('/summary')
    def summary():
        d = make_summary()
        return make_response(jsonify(d), 200)
    

    Inspiration taken from this comment in the Flask issue tracker.

    0 讨论(0)
提交回复
热议问题