跳转到主要内容

接受Django模板的ZipFile子类

项目描述

https://travis-ci.org/fcurella/django-zipfile.svg?branch=master

zipfile.Zipfile的子类,可用于Django模板。

使用方法

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.write_template('mimetype')
    container.write_template('META-INF/container.xml')
    container.write_template('chapter1.html', context=context)

    container.close()
    return response

您还可以指定多个模板的根目录

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

以及添加文件时的多个模板

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

TemplateZipFile将按照指定的顺序查找模板,首先按根目录,然后按模板名称。例如

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

如果找不到任何模板,write_template将引发一个TemplateDoesNotExist错误。

您可以通过optional=True将文件指定为可选

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

这样做将静默地吞咽TemplateDoesNotExist异常。

项目详情


下载文件

下载适合您平台的应用程序文件。如果您不确定要选择哪个,请了解更多关于安装包的信息。

源分布

django-zipfile-0.4.0.tar.gz (4.4 kB 查看散列值)

上传时间:

构建分布

django_zipfile-0.4.0-py2.py3-none-any.whl (3.7 kB 查看散列值)

上传时间 Python 2 Python 3

由以下支持