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.
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.
所有评论(0)