使用Flas禁用特定页上的缓存

2024-10-03 06:21:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个模板,显示了作者可以编辑/删除的各种条目。 用户可以单击“删除”删除其文章

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

添加这些标记不起作用,我想我的浏览器只是忽略了它们

<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" />

我正在启用缓存槽:

@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

有没有方法可以对特定页面禁用它?

编辑

我试着用包装纸:

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)

把我想要的页面包装在一个@no_cache decorator中,仍然没有成功。。。


Tags: no用户http编辑cachereturnresponsedef
1条回答
网友
1楼 · 发布于 2024-10-03 06:21:16

只有在特定页没有缓存控件头时,才能尝试添加缓存控件头:

@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

在你的页面代码中-例如:

@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'

关键是,不应该覆盖所有页面的@app.after_request中的头,而只覆盖那些没有显式关闭缓存的页面。

此外,您可能希望将添加头的代码移动到包装器(如@no_cache)中,以便可以像这样使用它:

 @app.route('/page_without_cache')
 @no_cache
 def page_without_cache():
   return 'hello'

相关问题 更多 >