我已启用调试,但没有显示任何内容。我看到的只是“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")
最佳答案
试试这个:
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 服务器应该处理它。
关于python - django动态 zipper 内部服务器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11039209/