Login

TemplateZipFile

Author:
fcurella
Posted:
December 13, 2011
Language:
Python
Version:
1.3
Score:
0 (after 0 ratings)

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
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import sys
from zipfile import ZipFile
from django.template import Context
from django.template.loader import get_template


class TemplateZipFile(ZipFile, object):
    def __init__(self, file, template_root=None, *args, **kwargs):
        self.template_root = template_root
        return super(TemplateZipFile, self).__init__(file, *args, **kwargs)

    def add_template(self, template_name, filename=None, context=None, compress_type=None):
        if compress_type is not None:
            if compress_type != self.compress_type and sys.version_info < (2, 7):
                raise "Python2.7 is required for individual file compression."
        if context is None:
            c = Context({})
        else:
            c = Context(context)

        if self.template_root is not None:
            template_name = self.template_root + template_name

        template = get_template(template_name)
        render = template.render(c)

        if filename is None:
            if self.template_root is not None:
                arc_filename = template_name.split(self.template_root)[1]
            else:
                arc_filename = template_name.split('/')[-1]
        if compress_type is not None:
            self.writestr(arc_filename, render, compress_type)
        else:
            self.writestr(arc_filename, render)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 8 months, 3 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 3 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
  5. Help text hyperlinks by sa2812 1 year, 5 months ago

Comments

Please login first before commenting.