将文件流式传输到Pylons中的HTTP响应 [英] Stream a file to the HTTP response in Pylons

查看:154
本文介绍了将文件流式传输到Pylons中的HTTP响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Pylons控制器操作需要将文件返回给客户端。 (该文件位于Web根目录之外,因此我不能直接链接到它。)最简单的方法当然是:

I have a Pylons controller action that needs to return a file to the client. (The file is outside the web root, so I can't just link directly to it.) The simplest way is, of course, this:

    with open(filepath, 'rb') as f:
        response.write(f.read())

这样可行,但对于大文件来说效率显然不高。最好的方法是什么?我无法在Pylons中找到任何方便的方法来流式传输文件的内容。我是否真的必须自己从头开始编写代码来读取块?

That works, but it's obviously inefficient for large files. What's the best way to do this? I haven't been able to find any convenient methods in Pylons to stream the contents of the file. Do I really have to write the code to read a chunk at a time myself from scratch?

推荐答案

我终于开始工作了使用 FileApp 类,感谢 Chris AtLee THC4k (来自这个答案)。这个方法还允许我设置Content-Length标题, Pylons有的东西很多问题,它使浏览器能够显示剩余时间的估计值。

I finally got it to work using the FileApp class, thanks to Chris AtLee and THC4k (from this answer). This method also allowed me to set the Content-Length header, something Pylons has a lot of trouble with, which enables the browser to show an estimate of the time remaining.

这是完整的代码:

def _send_file_response(self, filepath):
    user_filename = '_'.join(filepath.split('/')[-2:])
    file_size = os.path.getsize(filepath)

    headers = [('Content-Disposition', 'attachment; filename=\"' + user_filename + '\"'),
               ('Content-Type', 'text/plain'),
               ('Content-Length', str(file_size))]

    from paste.fileapp import FileApp
    fapp = FileApp(filepath, headers=headers)

    return fapp(request.environ, self.start_response)

这篇关于将文件流式传输到Pylons中的HTTP响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆