点击查看原文
再多的描述不如看代码,详细注释的代码。
#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')
