[英]Why is Flask ignoring Cache-Control?
我正在運行一個 Flask 應用程序,該應用程序包括一個每小時更新 memory 中的 json 變量的過程,並將該變量包含在其響應模板中。 我遇到了以下意外行為:
服務器代碼:
data = None
def updatejson():
global data
data = redditapi()
updatejson()
scheduler = BackgroundScheduler()
scheduler.add_job(func=updatejson, trigger="interval", minutes=60)
scheduler.start()
atexit.register(lambda: scheduler.shutdown())
app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
@app.route("/")
def hello():
global data
return render_template('index.html', data=data)
@app.after_request
def add_header(r):
r.headers["Cache-Control"] = "no-store"
return r
if __name__ == "__main__":
app.run(host='0.0.0.0')
我也試過設置下面的標題,但行為相同:
r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate, public, max-age=0'"
r.headers["Pragma"] = "no-cache"
r.headers["Expires"] = "0"
index.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" />
已確認的響應標頭在客戶端是正確的:
Cache-Control:no-store
Connection:keep-alive
Content-Encoding:gzip
Content-Type:text/html; charset=utf-8
Date:Thu, 26 Dec 2019 19:49:15 GMT
Server:nginx/1.14.0 (Ubuntu)
Transfer-Encoding:chunked
編輯: curl - 我報告如下:
HTTP/1.1 301 Moved Permanently
Server: nginx/1.14.0 (Ubuntu)
Date: Thu, 26 Dec 2019 22:24:29 GMT
Content-Type: text/html
Content-Length: 194
Connection: keep-alive
Location: https://pcsalesapp.com/
嘗試將過期 -1 和緩存控制添加到 Nginx,但行為仍然存在:
location / {
expires -1;
add_header Cache-Control "no-store";
include uwsgi_params;
uwsgi_pass unix:/home/jv/pcsalesapp/pcsalesapp.sock;
}
我是否也需要在 uwsgi 中解決這個問題?
為您的案例設置緩存控制的正確方法是:
@app.after_request
def add_header(r):
r.headers["Cache-Control"] = "no-store max-age=0"
return r
no-store
只會阻止緩存新資源,但不會阻止緩存響應來自早期請求的資源。 設置max-age=0
將強制緩存重新生效。
此外,按照以下方式設置緩存控制是實現此目的的糟糕方法,這就是它不起作用的原因:
r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate, public, max-age=0'"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.