Return JSON response from Flask view

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

提交回复
热议问题