python - django动态 zipper 内部服务器错误

标签 python django zip

我已启用调试,但没有显示任何内容。我看到的只是“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/

相关文章:

python - 使用 Beautiful Soup 解析 html 表单输入标签

python - 全局名称 'get_user_model' 未定义

django - 有什么办法可以将其转换为 django orm 吗?

r - 如何使用 R 以编程方式提取/解压缩 .7z (7-zip) 文件

php - 使用 EC2 压缩 S3 文件

java - 如何创建多部分 zip 文件并读回?

python - 查找多个 datetime.timedelta 对象的最小公倍数

python - 使用 df.merge 填充 df 中的新列给出奇怪的匹配项

python - 打开cv2读写视频错误1287

python - 使用 Django 类 View 获取当前登录用户?