我有以下视图代码,试图将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
Run Code Online (Sandbox Code Playgroud)
但是,这是我在浏览器中获得的响应:
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"
为了更好地说明这个问题,我已经包括一个微小.py和.pt文件Github上:https://github.com/thapar/zipper-fix
FileIter不是响应对象,就像您的错误消息所说的那样.它是一个可以用于响应体的迭代,就是这样.此外,它ZipFile可以接受文件对象,这比文件路径更有用.让我们尝试写入tmpfile,然后将该文件指针倒回到开头,并使用它写出而不做任何花哨的重命名.
import os
import zipfile
import tempfile
from pyramid.response import FileIter
def zipper(request):
_temp_path = request.registry.settings['_temp']
fp = tempfile.NamedTemporaryFile('w+b', dir=_temp_path, delete=True)
## creating zipfile and adding files
z = zipfile.ZipFile(fp, "w")
z.write('somefile1.txt')
z.write('somefile2.txt')
z.close()
# rewind fp back to start of the file
fp.seek(0)
response = request.response
response.content_type = 'application/zip'
response.app_iter = FileIter(fp)
return response
Run Code Online (Sandbox Code Playgroud)
我根据文档更改了模式,NamedTemporaryFile以'w+b'允许写入和读取文件.
| 归档时间: |
|
| 查看次数: |
1532 次 |
| 最近记录: |