10

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.

ifly6
  • 5,003
  • 2
  • 24
  • 47

2 Answers2

18

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.

ifly6
  • 5,003
  • 2
  • 24
  • 47
-2

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

Nukyi
  • 51
  • 5
  • This isn't JavaScript. This Django. – ifly6 Aug 20 '19 at 00:47
  • Yes. But what django does is "converting" your response into httpresponse, javascript and json, before sending it over to the client side. As you can see, you used "Content-Disposition", this is part of a json response. On top of that, you noticed that you are also using the "attachment" format. I believe that "Dataframe" does not have a format. It is a python-based object type but not an actual format. – Nukyi Aug 20 '19 at 00:50
  • That's correct, but you can write the Dataframe to the response by passing the response to `pd.to_csv` – ifly6 Aug 20 '19 at 01:31
  • Yes. It will be passed as a CSV format and not a Dataframe format. – Nukyi Aug 20 '19 at 07:44
  • On the receiving end, just use the pd.read_csv(URL_LINK) and you will be good to go. Do note that this only works as csv and not xlsx. – Nukyi Aug 20 '19 at 07:45
  • Are you trying to find out how to pass the Dataframe into the response ? Or receiving it? You did not really specific a question – Nukyi Aug 20 '19 at 07:47
  • Not sure how my question of `I have a DataFrame generated from a database. How do I provide a response wherein it downloads a CSV?` got turned into `How do I serialise a Pandas dataframe across the web to another computer`, but okay. I happened to discover the answer to this question a long time ago, which shouldn't be a surprise given its age. The answer is above. – ifly6 Aug 20 '19 at 13:47