Login

TemplateZipFile

Author:
fcurella
Posted:
December 13, 2011
Language:
Python
Version:
1.3
Tags:
template zipfile
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. Export queryset to Excel workbook by masida 9 months, 3 weeks ago
  2. pyText2Pdf - Python script to convert plain text into PDF file. Modified to work with streams. by vsergeyev 5 years, 8 months ago
  3. Decorator and context manager to override settings by jezdez 4 years, 1 month ago
  4. ExtendibleModelAdminMixin by dokterbob 5 years, 7 months ago
  5. File Mimetype Validator (Using python-magic) by BHSPitMonkey 1 year, 3 months ago

Comments

Please login first before commenting.