Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) 
like image 412
Nickpick Avatar asked Jul 28 '16 11:07

Nickpick


People also ask

How do I convert a pandas DataFrame to a CSV file?

By using pandas. DataFrame. to_csv() method you can write/save/export a pandas DataFrame to CSV File. By default to_csv() method export DataFrame to a CSV file with comma delimiter and row index as the first column.

How do I download a CSV file in flask?

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.


2 Answers

Set the Content-Disposition to tell the browser to download the 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 
like image 137
MaxU - stop WAR against UA Avatar answered Sep 21 '22 12:09

MaxU - stop WAR against UA


This is pretty much the same solution but you can just pass the same info into Response:

return Response(        df.to_csv(),        mimetype="text/csv",        headers={"Content-disposition":        "attachment; filename=filename.csv"}) 
like image 32
Liam Roberts Avatar answered Sep 18 '22 12:09

Liam Roberts