Skip to main content

A ZipFile subclass that accepts Django Templates

Project description

A subclass of zipfile.Zipfile that works with Django templates.


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;'

    container = TemplateZipFile(response, mode='w', compression=ZIP_DEFLATED, template_root='myapp/myzipskeleton/')

    container.write_template('chapter1.html', context=context)

    return response

You can also specify multiple roots for your templates:

container = TemplateZipFile(response, mode='w', compression=ZIP_DEFLATED, template_root=['myapp/myzipskeleton/override/', 'myapp/myzipskeleton/default/'])

as well as multiple templates when you add files:

container.write_template(['override.html', 'default.html'], filename="chapter1.html")

TemplateZipFile will look for templates in the specified order, first by root, then by template name. For example:

myzipfile = TemplateZipFile(response, mode='w', compression=ZIP_DEFLATED, template_root=['override/', 'default/'])
myzipfile.write_template(['two.txt', 'one.txt'], filename='myfile.txt')

# Will use the first existing template from ['override/two.txt', 'override/one.txt', 'default/two.txt', 'default/one.txt']

If none of the templates can be found, write_template will raise a TemplateDoesNotExist error.

You can specify a file as optional with optional=True

myzipfile.write_template(['two.txt', 'one.txt'], filename='myfile.txt', optional=True)

Doing so will silently swallow the TemplateDoesNotExist exception.

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for django-zipfile, version 0.4.0
Filename, size File type Python version Upload date Hashes
Filename, size django_zipfile-0.4.0-py2.py3-none-any.whl (3.7 kB) File type Wheel Python version py2.py3 Upload date Hashes View
Filename, size django-zipfile-0.4.0.tar.gz (4.4 kB) File type Source Python version None Upload date Hashes View

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring DigiCert DigiCert EV certificate Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page