我启用了调试,但它没有显示任何内容。我看到的只是“500内部服务器错误。 我在这个剧本中做错了什么?
蟒
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")
答案 0 :(得分: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服务器应该处理它。
答案 1 :(得分: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