我有以下视图代码,它尝试将 zip 文件“流式传输”到客户端以供下载:
import os
import zipfile
import tempfile
from pyramid.response import FileIter
def zipper(request):
_temp_path = request.registry.settings['_temp']
tmpfile = tempfile.NamedTemporaryFile('w', dir=_temp_path, delete=True)
tmpfile_path = tmpfile.name
## creating zipfile and adding files
z = zipfile.ZipFile(tmpfile_path, "w")
z.write('somefile1.txt')
z.write('somefile2.txt')
z.close()
## renaming the zipfile
new_zip_path = _temp_path + '/somefilegroup.zip'
os.rename(tmpfile_path, new_zip_path)
## re-opening the zipfile with new name
z = zipfile.ZipFile(new_zip_path, 'r')
response = FileIter(z.fp)
return response
但是,这是我在浏览器中得到的响应:
Could not convert return value of the view callable function newsite.static.zipper into a response object. The value returned was .
我想我没有正确使用 FileIter。
更新:
自从根据 Michael Merickel 的建议进行更新后,FileIter 函数工作正常。然而,仍然挥之不去的是客户端(浏览器)上出现的 MIME 类型错误:
Resource interpreted as Document but transferred with MIME type application/zip: "http://newsite.local:6543/zipper?data=%7B%22ids%22%3A%5B6%2C7%5D%7D"
为了更好地说明这个问题,我在 Github 上包含了一个小文件:.py
https ://github.com/thapar/zipper-fix.pt