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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3811595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:51:06  来源:igfitidea点击:

Flask/Werkzeug how to attach HTTP content-length header to file download

pythonhttp-headersdownloadflaskwerkzeug

提问by Jon Cox

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

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

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

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

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

但是,实际下载文件时,content-length并未设置HTTP 标头。所以用户不知道下载的文件有多大。

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-lengthheader in Flask.

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

Any ideas?

有任何想法吗?

采纳答案by Sean Vieira

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 objectand Flask's Response object.

请参阅:Werkzug 的 Headers 对象Flask 的 Response 对象

回答by raben

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

从 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

回答by Cyril N.

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