【问题标题】:How to prevent cached response (flask server, using chrome)如何防止缓存响应(烧瓶服务器,使用 chrome)
【发布时间】:2017-11-19 12:17:21
【问题描述】:

编辑:想通了,按F12,点击网络,勾选“禁用缓存”。

我有一个用于学习 d3 的基本烧瓶服务器。问题是 chrome 给了我一个我正在使用的缓存 javascript 文件,example.js。

请求方法:GET 状态码:200 OK(来自内存缓存)

服务器本身正在发送非缓存响应,我可以通过以下方式直接查看响应来查看:

/static/example.js

我在 application.py 中添加了这个以防止缓存。

@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

这是完整的代码

import os
import re
from flask import Flask, jsonify, render_template, request, url_for
from flask_jsglue import JSGlue

from flask import send_file

# configure application
app = Flask(__name__)
JSGlue(app)

# prevent cached responses
@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

@app.route("/<string:filename>")
def main(filename):
    """Render file."""
    return render_template(filename)

@app.route("/favicon.ico")
def favicon():
    filename = 'images/fav.png'
    return send_file(filename, mimetype='image/png')

感谢阅读。

【问题讨论】:

  • 我在 Chrome 中使用 Ctrl +F5 重新加载网页
  • 当我使用隐身窗口并打开检查工具 + 选择禁用缓存时,刷新工作。
  • 谢谢,我找到了问题所在,我阻止了来自服务器的缓存响应。但是,chrome 从它自己的缓存中给了我文件,所以我从检查/网络/禁用缓存中禁用了缓存。再次感谢。

标签: python google-chrome caching flask


【解决方案1】:

要防止来自浏览器的缓存响应: - 按 F12 或右键单击 > 检查 - 单击网络选项卡 - 勾选“禁用缓存”。

为了防止来自服务器的缓存响应:将以下定义添加到 application.py:

# prevent cached responses
if app.config["DEBUG"]:
    @app.after_request
    def after_request(response):
        response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate, public, max-age=0"
        response.headers["Expires"] = 0
        response.headers["Pragma"] = "no-cache"
        return response

【讨论】:

  • 禁用缓存也适用于 Firefox,任何人都可以查看。
  • 这不行,只有设置response.headers["Cache-Control"] = " no-store, max-age=0"才行,不需要response.headers["Expires"] = 0response.headers["Pragma"] = "no-cache"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-13
  • 1970-01-01
  • 2015-07-31
  • 2014-11-23
  • 1970-01-01
相关资源
最近更新 更多