flask的回调接入点

注意befor_request和after_request的装饰器下的函数内部逻辑

#!/usr/bin/env python
# -*- coding: utf-8 -*-


from flask import Flask, session
from datetime import datetime
from flask import request, render_template

app = Flask(__name__)



from werkzeug.contrib.cache import SimpleCache # 缓存类 SimpleCache

CACHE_TIMEOUT = 300

cache = SimpleCache() # 实例化 缓存类 SimpleCache
cache.timeout= CACHE_TIMEOUT

@app.before_request #将该函数return_cached()指定为一个在每个请求被处理之前调用的函数
def return_cached():
    '''
    如果客户端未提交任何参数,则在缓存中检查该页面是否存在,如果存在则终端该次请求的调用链
    直接将缓存结果返回给客户端
    '''
    if not request.values:
        response = cache.get(request.path)
        if response:
            print ("got the page from cache")
            return response
    print("Will load the page")
        
# 每一个请求被处理之后调用的函数
@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")


if __name__ == '__main__':
    app.run()


posted @ 2021-09-22 14:38  索匣  阅读(202)  评论(0编辑  收藏  举报