使用Flask禁用特定页面上的缓存

Luc*_*zzi 7 python caching flask

我有一个模板,显示作者可以编辑/删除的各种条目.用户可以单击"删除"删除其帖子

删除后,用户被重定向到条目页面,但该项目仍然存在,并且需要再次重新加载页面以显示删除效果.如果我禁用缓存问题消失了,但我真的希望在所有其他页面中都有缓存...

添加这些标签不起作用,我认为我的浏览器只是忽略它们

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
Run Code Online (Sandbox Code Playgroud)

我正在启用缓存槽:

@app.after_request
def add_header(response):    
response.headers['X-UA-Compatible'] = 'IE=Edge,chrome=1'
response.headers['Cache-Control'] = 'public, max-age=600'
return response
Run Code Online (Sandbox Code Playgroud)

有没有办法可以为特定页面禁用它?

编辑

建议我尝试使用包装器:

def no_cache(f):
    def new_func(*args, **kwargs):
        resp = make_response(f(*args, **kwargs))
        resp.cache_control.no_cache = True
        return resp
    return update_wrapper(new_func, f)
Run Code Online (Sandbox Code Playgroud)

并在@no_cache装饰器中包装我想要的缓存页面,仍然没有运气...

Nik*_*yar 6

只有在特定页面没有此类标头时,您才可以尝试添加缓存控制标头:

@app.after_request
def add_header(response):    
  response.headers['X-UA-Compatible'] = 'IE=Edge,chrome=1'
  if ('Cache-Control' not in response.headers):
    response.headers['Cache-Control'] = 'public, max-age=600'
  return response
Run Code Online (Sandbox Code Playgroud)

并在您的页面代码中 - 例如:

@app.route('/page_without_cache')
def page_without_cache():
   response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
   response.headers['Pragma'] = 'no-cache'
   return 'hello'
Run Code Online (Sandbox Code Playgroud)

关键是您不应该覆盖@app.after_request所有页面的标题- 仅适用于未明确关闭缓存的标题.

此外,您可能希望将代码添加标题移动到包装器,例如@no_cache- 所以您可以像这样使用它:

 @app.route('/page_without_cache')
 @no_cache
 def page_without_cache():
   return 'hello'
Run Code Online (Sandbox Code Playgroud)


Tri*_*tan 5

而 NikitaBaksalyar 的答案则指向了正确的方向。我很难让它发挥作用。页面代码给了我一个错误missing response

解决方案非常简单。使用make_response方法。

from flask import make_response
Run Code Online (Sandbox Code Playgroud)

对于每页缓存控制设置:

    @app.route('/profile/details', methods=['GET', 'POST'])
    def profile_details():
        ...<page specific logic>...
        response = make_response(render_template('profile-details.html'))
        response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
        response.headers['Pragma'] = 'no-cache'
        return response
Run Code Online (Sandbox Code Playgroud)

默认缓存控制设置:

    @app.after_request
    def add_header(response):
        response.headers['X-UA-Compatible'] = 'IE=Edge,chrome=1'
        if ('Cache-Control' not in response.headers):
            response.headers['Cache-Control'] = 'public, max-age=600'
        return response
Run Code Online (Sandbox Code Playgroud)