簡體   English   中英

為什么 Flask 忽略緩存控制?

[英]Why is Flask ignoring Cache-Control?

我正在運行一個 Flask 應用程序,該應用程序包括一個每小時更新 memory 中的 json 變量的過程,並將該變量包含在其響應模板中。 我遇到了以下意外行為:

  1. 初次訪問 web 頁面顯示的是僅在服務器啟動時實例化的數據。 最近每小時更新的數據將被忽略。
  2. 快速點擊重新加載 5-10 次將使瀏覽器保持最新狀態並顯示最新的 json 數據(僅重新加載一次或兩次無效)。
  3. 在瀏覽器顯示最新數據后,再次點擊重新加載將恢復到初始更新,就像它被緩存一樣。

服務器代碼:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM