Flask: Download a csv file on clicking a button
Here is one way to download a CSV file with no Javascript:
#!/usr/bin/python
from flask import Flask, Response
app = 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 POST
def plot_csv():
return send_file(
'outputs/Adjacency.csv',
mimetype='text/csv',
download_name='Adjacency.csv',
as_attachment=True
)
Prior to Flask 2.0, download_name
was called attachment_filename
.