Return JSON response from Flask view

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

    If you don't want to use jsonify for some reason, you can do what it does manually. Call flask.json.dumps to create JSON data, then return a response with the application/json content type.

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

    flask.json is distinct from the built-in json module. It will use the faster simplejson module if available, and enables various integrations with your Flask app.

提交回复
热议问题