1

我启用了调试,但它没有显示任何内容。我看到的只是“500 内部服务器错误。我在这个脚本中做错了什么?

Python

import zipfile
from zipfile import ZipFile
import cStringIO as StringIO
from django.http import HttpResponse
from django.core.servers.basehttp import FileWrapper

def zipit (request):
  files = ['/home/dbs/public_html/download/codex/video.html', '/home/dbs/public_html/download/audio/audio.html']
  buffer= StringIO.StringIO()
  z= zipfile.ZipFile( buffer, "w" )
  [z.write(f) for f in files]
  z.close()
  response = HttpResponse(FileWrapper(z), content_type='application/zip')
  response['Content-Disposition'] = 'attachment; filename=z.zip'
  return HttpResponse(response, mimetype="application/x-zip-compressed")
4

2 回答 2

3

试试这个:

import zipfile
from zipfile import ZipFile
import cStringIO as StringIO
from django.http import HttpResponse
from django.core.servers.basehttp import FileWrapper
import os

def zipit (request):
    files = ['/home/dbs/public_html/download/codex/video.html', '/home/dbs/public_html/download/audio/audio.html']
    buffer = StringIO.StringIO()
    z = zipfile.ZipFile(buffer, "w")
    [z.write(f, os.path.join('codex', os.path.basename(f))) for f in files]
    z.close()
    buffer.seek(0)
    response = HttpResponse(buffer.read())
    response['Content-Disposition'] = 'attachment; filename=z.zip'
    response['Content-Type'] = 'application/x-zip'
    return response

但请尽量不要让 django 返回它从未为此设计的二进制文件,您的 http 服务器应该处理它。

于 2012-06-14T18:51:57.180 回答
0

上述解决方法有效,但缺点是将整个 zip 加载到内存中并且没有利用文件系统。如果您正在创建一个大型存档,这可能会给您的应用程序带来严重的内存负担。这是一种类似的方法,可让您利用文件系统:

# imports omitted
def zipfileview(request):
    fd, fpath = tempfile.mkstemp()
    os.close(fd) # don't leave dangling file descriptors around...
    with zipfile.ZipFile(fpath, "w") as zip:

        # write files to zip here

        # when done send response from file
        response = HttpResponse(FileWrapper(open(fpath, 'rb')), mimetype="application/zip")
        response["Content-Disposition"] = "attachment; filename=myzip.zip"
        return response
于 2013-06-01T16:38:50.357 回答