如何使用 werkzeug 流式传输文件?

发布于 2024-10-20 04:37:18 字数 771 浏览 4 评论 0原文

我想通过 werkzeug 流式传输一个大文件。
目前我的 wsgi 应用程序如下所示:

from werkzeug.wrappers import Request, Response
from werkzeug.wsgi import ClosingIterator, wrap_file
import os

class Streamer(object):

    def __init__(self):
        pass

    def __call__(self, environ, start_response):
        request = Request(environ)
        filename = os.getcwd() + "/bigfile.xml"
        try:
            response = wrap_file(environ, open(filename) )
            return response
        except HTTPException, e:
            response = e
            return ClosingIterator(response(environ, start_response))

我不确定应该如何处理 返回的对象wrap_file 函数。

I want to stream a big file via werkzeug.
Currently my wsgi application looks like this:

from werkzeug.wrappers import Request, Response
from werkzeug.wsgi import ClosingIterator, wrap_file
import os

class Streamer(object):

    def __init__(self):
        pass

    def __call__(self, environ, start_response):
        request = Request(environ)
        filename = os.getcwd() + "/bigfile.xml"
        try:
            response = wrap_file(environ, open(filename) )
            return response
        except HTTPException, e:
            response = e
            return ClosingIterator(response(environ, start_response))

I'm not sure what I should do with the object returned by the wrap_file function.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

无戏配角 2024-10-27 04:37:18

我自己没有尝试过,但我认为以下方法会起作用。

g = file(path_to_bigfile) # or any generator
return Response(g, direct_passthrough=True)

Haven't tried myself but I think following will work.

g = file(path_to_bigfile) # or any generator
return Response(g, direct_passthrough=True)
十秒萌定你 2024-10-27 04:37:18

以防万一有人还想:
1.保留文件名
2. 不带页面重定向的问题下载

# file_name assumed to be known
# file_path assumed to be known
file_size = os.path.getsize(file_path)
fh = file(file_path, 'rb')
return Response(fh,
                mimetype='application/octet-stream',
                headers=[
                    ('Content-Length', str(file_size)),
                    ('Content-Disposition', "attachment; filename=\"%s\"" % file_name),
                ],
                direct_passthrough=True)

Just in case one would additionally like to:
1. preserve the file name
2. issue download without page redirect

# file_name assumed to be known
# file_path assumed to be known
file_size = os.path.getsize(file_path)
fh = file(file_path, 'rb')
return Response(fh,
                mimetype='application/octet-stream',
                headers=[
                    ('Content-Length', str(file_size)),
                    ('Content-Disposition', "attachment; filename=\"%s\"" % file_name),
                ],
                direct_passthrough=True)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文