ifly6
ifly6

Reputation: 5331

Pandas CSV to Django Response

I have a DataFrame generated from a database. How do I provide a response wherein it downloads a CSV?

Basically,

df = magic_dataframe_supplier()
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=export.csv'

# ... type mapping code ...

return response

I've got a working version with csv.writer but for obvious reasons, that is not a DataFrame. And I'm unclear on how exactly I can turn a df into such an object.

Upvotes: 11

Views: 6359

Answers (2)

ifly6
ifly6

Reputation: 5331

Given:

df = magic_dataframe_supplier()
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=export.csv'  # alter as needed

Just write:

df.to_csv(path_or_buf=response)  # with other applicable parameters
return response

Pandas writes the data frame to CSV in the response buffer and then Django serves the response.

Compression. Pandas does not permit the passing of non-none compression parameters, as it cannot determine the compression type from a buffer, which is not a path. Instead, for compression, one would have to write the file to a text wrapper which is then compressed using Python's gzip library. That object would then be served as the archive. Code similar to this, adapted for Django, would be necessary.

Edit. 2024-04-25. I think, but am not sure, that if your server is properly configured with something like Apache mod_deflate it will compress your document on the fly and serve it (though recompression will occur every time).

Upvotes: 20

Nukyi
Nukyi

Reputation: 51

I believe that the object type "DataFrame" does not exist in javascript. You may want to try JSON instead to transmit your data.

Upvotes: -2

Related Questions