| 1 | Return a dynamically created zip file in your !HttpResponse. |
| 2 | {{{ |
| 3 | #!python |
| 4 | def view_that_returns_zipped_file(request): |
| 5 | response = HttpResponse(mimetype='application/zip') |
| 6 | response['Content-Disposition'] = 'filename=all_things.zip' |
| 7 | #first assemble your files |
| 8 | files = [] |
| 9 | for thing in Thing.objects.all(): |
| 10 | files.append(("%s.pdf" % (thing.id,), thing.biggish_file())) |
| 11 | #now add them to a zip file |
| 12 | #note the zip only exist in memory as you add to it |
| 13 | buffer = StringIO() |
| 14 | zip = zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) |
| 15 | for name, f in files: |
| 16 | zip.writestr(name, f) |
| 17 | zip.close() |
| 18 | buffer.flush() |
| 19 | #the import detail--we return the content of the buffer |
| 20 | ret_zip = buffer.getvalue() |
| 21 | buffer.close() |
| 22 | response.write(ret_zip) |
| 23 | return response |
| 24 | }}} |