Return JSON response from Flask view

前端 未结 15 2584
时光取名叫无心
时光取名叫无心 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 06:08

    Pass the summary data to the jsonify function, which returns a JSON response.

    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.

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

    if its a dict, flask can return it directly (Version 1.0.2)

    def summary():
        d = make_summary()
        return d, 200
    
    0 讨论(0)
  • 2020-11-21 06:12

    I like this way:

        @app.route("/summary")
        def summary():
            responseBody = { "message": "bla bla bla", "summary": make_summary() }
            return make_response(jsonify(responseBody), 200)
    
    0 讨论(0)
提交回复
热议问题