Flask: Download a csv file on clicking a button [duplicate] Flask: Download a csv file on clicking a button [duplicate] flask flask

Flask: Download a csv file on clicking a button [duplicate]


Here is one way to download a CSV file with no Javascript:

#!/usr/bin/pythonfrom flask import Flask, Responseapp = Flask(__name__)@app.route("/")def hello():    return '''        <html><body>        Hello. <a href="/getPlotCSV">Click me.</a>        </body></html>        '''@app.route("/getPlotCSV")def getPlotCSV():    # with open("outputs/Adjacency.csv") as fp:    #     csv = fp.read()    csv = '1,2,3\n4,5,6\n'    return Response(        csv,        mimetype="text/csv",        headers={"Content-disposition":                 "attachment; filename=myplot.csv"})app.run(debug=True)


You can use flask.send_file() to send a static file:

from flask import send_file@app.route('/getPlotCSV') # this is a job for GET, not POSTdef plot_csv():    return send_file('outputs/Adjacency.csv',                     mimetype='text/csv',                     attachment_filename='Adjacency.csv',                     as_attachment=True)


Firstly you need to import from flask make_response, that will generate your response and create variable, something like response.Secondly, make response.content_type = "text/csv"Thirdly - return your response.