Flask回掉接入点简单实现静态页面缓存

来源:互联网 发布:韩都衣舍淘宝 编辑:程序博客网 时间:2024/06/06 02:57

再多的描述不如看代码,详细注释的代码。

#coding:utf8from 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')

这里写图片描述

原创粉丝点击