nickpick nickpick - 4 months ago 135
Python Question

Use Flask to convert a Pandas dataframe to CSV and serve a download

I have a Pandas dataframe in my Flask app that I want to return as a CSV file.

return Response(df.to_csv())


The problem is that the output appears in the browser instead of downloading as a separate file. How can I change that?

I tried the following as well but it just gave empty output.

response = make_response(df.to_csv())
response.headers['Content-Type'] = 'text/csv'
return Response(response)

Answer

you can set Content-Disposition as attachment which will allow to download the CSV file instead of showing its content on the page:

resp = make_response(df.to_csv())
resp.headers["Content-Disposition"] = "attachment; filename=export.csv"
resp.headers["Content-type"] = "text/csv"
return resp

or you can use io.StringIO:

from io import StringIO

out = StringIO()
df.to_csv(out)
resp = make_response(out.getvalue())
resp.headers["Content-Disposition"] = "attachment; filename=export.csv"
resp.headers["Content-type"] = "text/csv"
return resp
Comments