Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating file to download with Django

Tags:

python

django

Is it possible to make a zip archive and offer it to download, but still not save a file to the hard drive?

like image 702
Josh Hunt Avatar asked May 25 '09 22:05

Josh Hunt


People also ask

How do I upload and download in Django?

Add template folder in the Django folder and provide its path in django_folder > settings.py. Add file named as urls.py in the app folder and provide its path in django_project > urls.py. Add the function in app_folder > views.py. Provide the URL path in app> urls.py to the functions created in views.py.

How can I download Excel file in Django?

Download data as Excel file in Django: It is always recommended to user virtual environment. Once virtual environment is activated, Run this command to add xlwt package. Inside your view, import xlwt package. Use below code in your view in views.py file to create and download excel file.


2 Answers

To trigger a download you need to set Content-Disposition header:

from django.http import HttpResponse from wsgiref.util import FileWrapper  # generate the file response = HttpResponse(FileWrapper(myfile.getvalue()), content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=myfile.zip' return response 

If you don't want the file on disk you need to use StringIO

import cStringIO as StringIO  myfile = StringIO.StringIO() while not_finished:     # generate chunk     myfile.write(chunk) 

Optionally you can set Content-Length header as well:

response['Content-Length'] = myfile.tell() 
like image 175
muhuk Avatar answered Sep 18 '22 12:09

muhuk


You'll be happier creating a temporary file. This saves a lot of memory. When you have more than one or two users concurrently, you'll find the memory saving is very, very important.

You can, however, write to a StringIO object.

>>> import zipfile >>> import StringIO >>> buffer= StringIO.StringIO() >>> z= zipfile.ZipFile( buffer, "w" ) >>> z.write( "idletest" ) >>> z.close() >>> len(buffer.getvalue()) 778 

The "buffer" object is file-like with a 778 byte ZIP archive.

like image 33
S.Lott Avatar answered Sep 20 '22 12:09

S.Lott