接受django模板的zipfile子类

django-zipfile的Python项目详细描述


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

使用django模板的zipfile.Zipfile的子类。

用法:

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

如果找不到模板,^ {TT2}$将引发一个TeMeTeDeEntExtistor错误。

可以使用optional=True

将文件指定为可选文件
myzipfile.write_template(['two.txt', 'one.txt'], filename='myfile.txt', optional=True)
这样做会悄悄地吞下那个例外的例外。

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
字符串Java字母替换无效   java Spring Roo JPA MS SQL Server无法打开JPA EntityManager组织。冬眠例外GenericJDBCException:无法打开连接   在scala中使用JavaWS对大型数据文件进行java流式处理   Java编译器是否将字节和短字符识别为文本?   java无法查找符号错误,空指针   mongodb在Java中重用数据库连接   java将多个StringArray从字符串文件获取到活动中   java是一个变量,它只保存最后一次鼠标单击的坐标   c#尺寸有限;添加、删除和洗牌   java如何在Android中显示来自资产文件夹的文本文件中的文本   Android应用程序中的java Tensorflow Lite自定义对象检测模型错误   java如何在foreachloop中使用scanner将来自命令行的输入存储到数组中   java如何定义一个好的存储库接口   Android中的java解析动态json对象