Sometimes, we want to download a csv file on clicking a button with Python Flask.
in this article, we’ll look at how to download a csv file on clicking a button with Python Flask.
How to download a csv file on clicking a button with Python Flask?
To download a csv file on clicking a button with Python Flask, we can add a link that goes to the view that returns the csv as the response.
For instance, we write
from flask import Flask, Response
app = Flask(__name__)
@app.route("/")
def hello():
return '''
<html>
<body>
<a href="/get_csv">Click me.</a>
</body>
</html>
'''
@app.route("/get_csv")
def get_csv():
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)
to create the hello
route that renders the HTML with the link.
Then add the get_csv
view that returns the csv as the response by creating a Response
object with mimetype
set to 'text/csv'
and the csv
as the content.
Now when we click on the link, the csv should be downloaded as myplot.csv.
Conclusion
To download a csv file on clicking a button with Python Flask, we can add a link that goes to the view that returns the csv as the response.