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')

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值