我有以下视图代码,试图将zipfile“流式”传输到客户端以供下载:
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
和{
当前的金字塔版本有两个方便类用于这个用例-FileResponse和FileIter。下面的代码段将提供一个静态文件。我运行这段代码-下载的文件名为“download”,就像视图名一样。若要更改文件名及其他内容,请设置内容处置标头或查看的参数金字塔。反应。反应. 在
文件: http://docs.pylonsproject.org/projects/pyramid/en/latest/api/response.html#
提示:如果可能,从视图中提取Zip逻辑
FileIter
不是响应对象,就像您的错误消息所说的那样。它是一个可用于响应体的iterable,仅此而已。另外,ZipFile
可以接受file对象,这在这里比文件路径更有用。让我们尝试写入tmpfile
,然后将该文件指针倒回起始位置,并使用它在不进行任何花哨重命名的情况下写出。在根据文档,我将
NamedTemporaryFile
上的模式改为'w+b'
,以允许文件写入和读取。在相关问题 更多 >
编程相关推荐