Return JSON response from Flask view

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

    As of version 1.1.0 Flask, if a view returns a dict it will be turned into a JSON response.

    @app.route("/users", methods=['GET'])
    def get_user():
        return {
            "user": "John Doe",
        }
    
    0 讨论(0)
  • 2020-11-21 05:47

    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'.

    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
    
    0 讨论(0)
  • 2020-11-21 05:55

    Pass keyword arguments to flask.jsonify and they will be output as a JSON object.

    @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
    }
    

    If you already have a dict, you can pass it directly as jsonify(d).

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-21 05:56

    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.

    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.

    0 讨论(0)
  • 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"
    
    0 讨论(0)
提交回复
热议问题