1. 程式人生 > >Flask回掉接入點簡單實現靜態頁面快取

Flask回掉接入點簡單實現靜態頁面快取

再多的描述不如看程式碼,詳細註釋的程式碼。

#coding:utf8
from werkzeug.contrib.cache import SimpleCache
#引入werkzeug.contrib.cache裡面的快取類
from flask import request,render_template
#引入模板
CACHE_TIMEOUT = 300
#定義個屬性超時
cache = SimpleCache()
#生成一個SimpleCache物件
cache.timeout =CACHE_TIMEOUT
#設定超時時間
@app.before_request
#此函式在所有i請求之前執行
def return_cached(): if not request.values: #如果使用者沒有提交引數,values是存提交引數。 response =cache.get(request.path) #就在快取中檢查當前頁面是否存在 if response: #如果存在 return response #返回快取 @app.after_request #在所有請求最後執行 def cache_response(response): if
not request.values: #如果客戶端未提交任何引數 cache.set(request.path,response,CACHE_TIMEOUT) #認為此次返回結果具有典型性,將其存到快取物件,以便後續訪問 return response #執行返回 @app.route("/get/index") def index(): return render_template('index.html')

這裡寫圖片描述