2

I've made a simple JSON API using django-rest-framework, and I'd like to be able to download the 5 collections as one zipfile containing the collections as JSON files. (my app requires this offline dump of data).

I'm thinking of writing a view, served at, say, /download/ that bundles up the output from all my MyModelList.as_view()s in a zip and serves it.

What is the best way of doing this? I could use urllib/Requests to query my API directly, but it seems a long way round, to invoke the whole http stack...

Many thanks!

0atman
  • 3,298
  • 4
  • 30
  • 46

1 Answers1

3

You could use the MyModelList.as_view()(request, format="json").rendered_content you mention. Depending on your setup, you could also call a serializer directly instead of going all the way through your model. This, of course, depends on whether you do anything special in your view or whether you just pass along serialized model data.

For zipping up those files, use Python's zipfile module. See https://stackoverflow.com/a/9644831/27401 and https://stackoverflow.com/a/908293/27401 for some additional hints. A summary:

  • Use StringIO to create a file-like object (instead of a temporary file).

  • Use zipfile's .writestr('filename-in-zip.json', your_json_string) on that StringIO to add content.

  • When returning the zipfile as a django response, don't forget to set the Content-Disposition header as shown in https://stackoverflow.com/a/909088/27401

Community
  • 1
  • 1
Reinout van Rees
  • 13,486
  • 2
  • 36
  • 68