Python 使用 Flask,如何修改所有输出的 Cache-Control 标头?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23112316/
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-19 02:16:50  来源:igfitidea点击:

Using Flask, how do I modify the Cache-Control header for ALL output?

pythonhttpflask

提问by wuxiekeji

I tried using this

我试过用这个

@app.after_request
def add_header(response):
    response.headers['Cache-Control'] = 'max-age=300'
    return response

But this causes a duplicate Cache-Control header to appear. I only want max-age=300, NOT the max-age=1209600 line!

但这会导致出现重复的 Cache-Control 标头。我只想要 max-age=300,而不是 max-age=1209600 行!

$ curl -I http://my.url.here/
HTTP/1.1 200 OK
Date: Wed, 16 Apr 2014 14:24:22 GMT
Server: Apache
Cache-Control: max-age=300
Content-Length: 107993
Cache-Control: max-age=1209600
Expires: Wed, 30 Apr 2014 14:24:22 GMT
Content-Type: text/html; charset=utf-8

采纳答案by Martijn Pieters

Use the response.cache_controlobject; this is a ResponseCacheControl()instanceletting you set various cache attributes directly. Moreover, it'll make sure not to add duplicate headers if there is one there already.

使用response.cache_control对象;这是一个让您直接设置各种缓存属性的ResponseCacheControl()实例。此外,如果已经有一个标题,它会确保不添加重复的标题。

@app.after_request
def add_header(response):
    response.cache_control.max_age = 300
    return response

回答by aldel

You can set the default value for all static fileswhen you create the Flask application:

您可以在创建 Flask 应用程序时为所有静态文件设置默认值:

app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 300

Note that if you modify request.cache_controlin after_request, as in the accepted answer, this will also modify the Cache-Controlheader for static files and may override the behavior you set as I showed above. I'm currently using the following code to completely disable caching for dynamically generated content but not static files:

请注意,如果您像在接受的答案中那样修改request.cache_controlin after_request,这也会修改Cache-Control静态文件的标头,并且可能会覆盖您设置的行为,如我上面所示。我目前正在使用以下代码完全禁用动态生成内容的缓存,而不是静态文件:

# No cacheing at all for API endpoints.
@app.after_request
def add_header(response):
    # response.cache_control.no_store = True
    if 'Cache-Control' not in response.headers:
        response.headers['Cache-Control'] = 'no-store'
    return response

Not completely sure this is the best way, but it's working for me so far.

不完全确定这是最好的方法,但到目前为止它对我有用。