【问题标题】:Disabling caching in Flask [duplicate]在 Flask 中禁用缓存 [重复]
【发布时间】:2016-03-08 02:45:08
【问题描述】:

我有一些缓存问题。我正在运行非常小的网络应用程序,它读取一帧,将其保存到磁盘,然后在浏览器窗口中显示。

我知道,这可能不是最好的解决方案,但是每次我用相同的名称保存这个读取帧时,任何浏览器都会缓存它。

我尝试使用 html 元标记 - 没有成功:

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

另外,我已经尝试过这个(特定于烧瓶):

resp.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
resp.headers["Pragma"] = "no-cache"
resp.headers["Expires"] = "0"

这就是我尝试修改 resp 标头的方式:

r = make_response(render_template('video.html', video_info=video_info))

r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
r.headers["Pragma"] = "no-cache"
r.headers["Expires"] = "0"

Google Chrome 和 Safari 仍然进行缓存。

这里可能有什么问题?

【问题讨论】:

    标签: python caching flask


    【解决方案1】:

    您可以使用 ctrl + F5 绕过缓存

    【讨论】:

    • 你是对的,但你真的要告诉所有访问你网站的人每次加载你的页面时都按 CTRL + F5 吗?
    【解决方案2】:

    结合 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 在 python 文件中

    和 chrome 浏览器的硬重载(command + shift + R)对我有用,因为 Chrome 似乎缓存了静态文件

    【讨论】:

      【解决方案3】:

      如果你总是遇到同样的问题,那就是 Flask 没有看到 JS 和 CSS 文件中的更新,因为默认情况下,Flask 的 max-age 值为 12 小时。您可以将其设置为 0 来解决这样的问题:

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

      详情请参阅its documentation

      【讨论】:

      • 这是一个更简单的解决方案,我需要做的只是
      【解决方案4】:

      好的,

      终于可以解决这个问题了:

      @app.after_request
      def add_header(r):
          """
          Add headers to both force latest IE rendering engine or Chrome Frame,
          and also to cache the rendered page for 10 minutes.
          """
          r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
          r.headers["Pragma"] = "no-cache"
          r.headers["Expires"] = "0"
          r.headers['Cache-Control'] = 'public, max-age=0'
          return r
      

      如果你添加这个,这个函数将在每个请求完成后调用。请看here

      我会很高兴,如果有人能解释为什么这个标题覆盖在页面处理程序中不起作用?

      谢谢。

      【讨论】:

      • 您告诉浏览器不要缓存包含 video.html 内容的响应。您需要告诉它不要缓存包含框架本身的响应。
      • 请注意,您将在倒数第二行的第一行覆盖r.headers["Cache-Control"]。如此有效地,您的回复只会将'public, max-age=0' 设置为Cache-Control
      • 相关:现在可以使用 Flask 1.0.2 访问 Response 实例的底层 cache_control 对象,然后将 no_cache 字段设置为 @,而不是手动指定标头987654332@(及其他相关领域)。见stackoverflow.com/a/23115561/2745495
      • 来自 MDN 文档,看起来 no-store 是唯一需要的东西,更好的做法是仅在设置 Cache-Control:developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control 时使用。 IE。 Cache-Control: no-store 在服务器响应中防止缓存。
      猜你喜欢
      • 2011-03-02
      • 2014-01-20
      • 1970-01-01
      • 2010-11-09
      • 2014-09-28
      • 1970-01-01
      • 2015-04-22
      • 1970-01-01
      • 2012-05-08
      相关资源
      最近更新 更多