如何在Flask中修改所有输出的Cache-Control头?

48 投票
3 回答
48590 浏览
提问于 2025-04-18 02:59

我试着使用这个

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

但是这样会导致出现重复的 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

3 个回答

0

我在我的views.py和auth.py文件中使用这个:

def no_cache(resp):
    resp.headers['Cache-Control'] = 'max-age=1, No-Store'

@views.route('/', METHOD=['GET'])
def home_page():
    resp = make_response(render_template("somepage.html", user=current_user), 200)
    no_cache(resp)
    return resp
46

在创建Flask应用的时候,你可以为所有的静态文件设置一个默认值:

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

需要注意的是,如果你在after_request中修改了request.cache_control,就像被接受的答案中提到的那样,这也会改变静态文件的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

我不太确定这是否是最好的方法,但到目前为止对我来说是有效的。

82

使用 response.cache_control 对象;这个对象是一个 ResponseCacheControl() 实例,可以让你直接设置各种缓存属性。而且,它还会确保如果已经有一个相同的头部,就不会重复添加。

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

撰写回答