Use Flask to Convert Pandas Frame to CSV and Download

I have a Pandas framework in my Flask application 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 to change this?

I tried the following, but it just gave an empty output.

 response = make_response(df.to_csv()) response.headers['Content-Type'] = 'text/csv' return Response(response) 
+6
source share
2 answers

Install Content-Disposition to tell the browser to download the file, rather than displaying its contents 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 
+9
source

set the content location and use stringIO to convert data to stream, below is the code to achieve,

 execel_file = StringIO.StringIO() filename = "%s.csv" % ('output file') df.to_csv(execel_file, encoding='utf-8') csv_output = execel_file.getvalue() execel_file.close() resp = make_response(csv_output) resp.headers["Content-Disposition"] = ("attachment; filename=%s" % filename) resp.headers["Content-Type"] = "text/csv" return resp 
0
source

All Articles