Flask/Werkzeug 如何将 HTTP 内容长度标头附加到文件下载

发布于 2024-09-25 08:51:16 字数 422 浏览 0 评论 0 原文

我正在使用 Flask(基于 Werkzeug),它使用 Python。

用户可以下载文件,我正在使用 send_from_directory -函数

然而,当实际下载文件时,HTTP 标头 content-length 并未设置。因此用户不知道正在下载的文件有多大。

我可以在 Python 中使用 os.path.getsize(FILE_LOCATION) 来获取文件大小(以字节为单位),但找不到设置 content-length 标头的方法烧瓶。

有什么想法吗?

I am using Flask (based on Werkzeug) which uses Python.

The user can download a file, I'm using the send_from_directory-function.

However when actually downloading the file, the HTTP header content-length is not set. So the user has no idea how big the file being downloaded is.

I can use os.path.getsize(FILE_LOCATION) in Python to get the file size (in bytes), but cannot find a way to set the content-length header in Flask.

Any ideas?

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

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

发布评论

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

评论(3

婴鹅 2024-10-02 08:51:16

我也需要这个,但是对于每个请求,所以这就是我所做的(基于文档):

@app.after_request
def after_request(response):
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response

I needed this also, but for every requests, so here's what I did (based on the doc) :

@app.after_request
def after_request(response):
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response
亽野灬性zι浪 2024-10-02 08:51:16

从版本 0.6 开始,向响应对象添加标头的规范方法是通过 make_response 方法(请参阅 Flask 文档)。

def index():
    response = make_response(render_template('index.html', foo=42))
    response.headers['X-Parachutes'] = 'parachutes are cool'
    return response

Since version 0.6 the canonical way to add headers to a response object is via the make_response method (see Flask docs).

def index():
    response = make_response(render_template('index.html', foo=42))
    response.headers['X-Parachutes'] = 'parachutes are cool'
    return response
入怼 2024-10-02 08:51:16

我相信你会做这样的事情(未经测试):

from flask import Response
response = Response()
response.headers.add('content-length', str(os.path.getsize(FILE_LOCATION)))

请参阅: Werkzug 的标头objectFlask 的 Response 对象

I believe you'd do something like this (untested):

from flask import Response
response = Response()
response.headers.add('content-length', str(os.path.getsize(FILE_LOCATION)))

See: Werkzug's Headers object and Flask's Response object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文