在Django视图中压缩文件并为它们提供服务

时间:2012-03-10 06:47:31

标签: python django django-views zipfile

首先,我想说我知道从django提供文件很糟糕,但我的情况只能由django处理,所以我选择它来提供压缩文件。在我的models.py我有一个模型

class Documents(models.Model):
    filename = models.CharField(max_length=100)
    document = models.FileField(upload_to='docs')
    allowedGroup = models.ManyToManyField(Group)

因此,当普通用户登录时,将根据他/她的组显示他有权限的文档。我希望用户能够一次下载多个文档(文件)。所以我做的是添加了此处理程序,用于将多个文件作为zip文件下载:

我使用此Django Snippet来创建此视图

  def Download_selected_document(self, request, queryset):  

    if len(queryset)>1:

        temp = tempfile.TemporaryFile()
        archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)
        for i in queryset:
            ##Reading the file content
            content = open(settings.MEDIA_ROOT+str(i.document),'rb').read()
            ##name is name of file like "abc.docx"
            name = str(queryset[0].document)[10:]
            ##At this like it gives me error
            archive.write(content,name)

        archive.close()
        wrapper = FileWrapper(temp)
        response = HttpResponse(wrapper, content_type='application/zip')
        response['Content-Disposition'] = 'attachment; filename=test.zip'
        response['Content-Length'] = temp.tell()
        temp.seek(0)
        return response

    else:
        self.message_user(request, "You must select multiple documents for downloading.")

我得到的错误是:必须是没有NULL字节的编码字符串,而不是str

Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in wrapper
  307.                 return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapped_view
  93.                     response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
  79.         response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\contrib\admin\sites.py" in inner
  197.             return view(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapper
  28.             return bound_func(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapped_view
  93.                     response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in bound_func
  24.                 return func(self, *args2, **kwargs2)
File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in changelist_view
  1079.                 response = self.response_action(request, queryset=cl.get_query_set())
File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in response_action
  836.             response = func(self, request, queryset)
File "C:\Documents and Settings\Anshul\Desktop\online.in\online\..\online\assessment\admin.py" in Download_selected_document
  82.             archive.write(content,name)
File "C:\Python27\lib\zipfile.py" in write
  1031.         st = os.stat(filename)

Exception Type: TypeError at /admin/assessment/userdocuments/
Exception Value: must be encoded string without NULL bytes, not str

我不知道该如何解决这个问题。请帮忙

1 个答案:

答案 0 :(得分:3)

使用

zipfile.ZipFile().writestr(archived_name, content_to_be_archived)

而不是

zipfile.ZipFile().write(filename_to_load_content_from, archived_name=None) 

所以快速修复可能是

archive.write(content,name) => archive.writestr(name, content)

此外,您可能需要检查

  • 如果压缩文件的大小通常很小,则使用StringIO而不是tempfile
  • 由于HttpResponse对象是一个类似文件的对象,你可以直接压缩它
  • 在nginx中使用XSendfile或X-Accel-Redirect来帮助传输响应的文件,而不是依赖于Django本身