Return JSON response from Flask view

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

    In Flask 1.1, if you return a dictionary and it will automatically be converted into JSON. So if make_summary() returns a dictionary, you can

    from flask import Flask
    
    app = Flask(__name__)
    
    @app.route('/summary')
    def summary():
        d = make_summary()
        return d
    

    The SO that asks about including the status code was closed as a duplicate to this one. So to also answer that question, you can include the status code by returning a tuple of the form (dict, int). The dict is converted to JSON and the int will be the HTTP Status Code. Without any input, the Status is the default 200. So in the above example the code would be 200. In the example below it is changed to 201.

    from flask import Flask
    
    app = Flask(__name__)
    
    @app.route('/summary')
    def summary():
        d = make_summary()
        return d, 201  # 200 is the default
    

    You can check the status code using

    curl --request GET "http://127.0.0.1:5000/summary" -w "\ncode: %{http_code}\n\n"
    

提交回复
热议问题