首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用pyramid.response.FileIter

如何使用pyramid.response.FileIter
EN

Stack Overflow用户
提问于 2013-04-05 06:10:46
回答 2查看 1.8K关注 0票数 4

我有以下视图代码,试图将一个the文件“流”到客户端下载:

代码语言:javascript
复制
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。

更新:

自从使用Merickel的建议进行更新之后,FileIter函数就可以正常工作了。然而,仍然挥之不去的是客户机(浏览器):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"上出现的MIME类型错误。

为了更好地说明这个问题,我在Github:https://github.com/thapar/zipper-fix上包含了一个很小的.py.pt文件。

EN

回答 2

Stack Overflow用户

发布于 2013-04-05 15:12:04

FileIter不是响应对象,就像您的错误消息说的那样。它是一个可迭代的,可以用于响应体,仅此而已。此外,ZipFile还可以接受一个文件对象,这在这里比文件路径更有用。让我们尝试将该文件指针写入tmpfile,然后将该文件指针还原回起始位置,并使用它进行写入,而不进行任何花哨的重命名。

代码语言:javascript
复制
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

我根据文档将NamedTemporaryFile上的模式更改为'w+b',允许将文件写入从读取的文件。

票数 9
EN

Stack Overflow用户

发布于 2013-04-05 07:40:48

目前的金字塔版本有两个方便的类为这个用例- FileResponse,FileIter。下面的片段将提供一个静态文件。我运行了这个代码-下载的文件名为“下载”,就像视图名一样。若要更改文件名和更多内容,请设置内容配置头或查看pyramid.response.Response的参数。

代码语言:javascript
复制
from pyramid.response import FileResponse

@view_config(name="download")
def zipper(request):    
    path = 'path_to_file'
    return FileResponse(path, request) #passing request is required

博士:http://docs.pylonsproject.org/projects/pyramid/en/latest/api/response.html#

提示:如果可能,从视图中提取Zip逻辑

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15827090

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档