Snippet List
TemplateZipFile is a class for creating ZipFiles out of Django templates.
Usage example:
from zipfile import ZIP_DEFLATED
from django_zipfile import TemplateZipFile
def myview(request, object_id):
obj = get_object_or_404(MyModel, pk=object_id)
context = {
'object': obj
}
response = HttpResponse(mimetype='application/octet-stream')
response['Content-Disposition'] = 'attachment; filename=myfile.zip'
container = TemplateZipFile(response, mode='w', compression=ZIP_DEFLATED, template_root='myapp/myzipskeleton/')
container.add_template('mimetype')
container.add_template('META-INF/container.xml')
container.add_template('chapter1.html', context=context)
container.close()
return response
See code
- zipfile
- auto
- writedir
- py
- pyc
This snippet demonstrates how you can send a file (or file-like object) through Django without having to load the whole thing into memory. The FileWrapper will turn the file-like object into an iterator for chunks of 8KB.
This is a full working example. Start a new app, save this snippet as views.py, and add the views to your URLconf. The send_file view will serve the source code of this file as a plaintext document, and the send_zipfile view will generate a Zip file with 10 copies of it.
Use this solution for dynamic content only, or if you need password protection with Django's user accounts. Remember that you should serve static files directly through your web server, not through Django:
http://www.djangoproject.com/documentation/modpython/#serving-media-files
- sendfile
- zipfile
- tempfile
- temporaryfile
- filewrapper
3 snippets posted so far.