from flask import Flask from flask_cache import Cache from flask_script import Manager app = Flask(__name__) manage = Manager(app) #缓存类型 app.config['CACHE_TYPE'] = 'redis' #主机 app.config['CACHE_REDIS_HOST'] = '127.0.0.1' #端口 app.config['CACHE_REDIS_PORT'] = 6379 #数据库 app.config['CACHE_REDIS_DB'] = 1 #创建缓存对象 cache = Cache(app,with_jinja2_ext=False) @app.route('/index/') def index(): return '欢迎' #创建缓存视图函数 @app.route('/set_cache/') #timeout:指定缓存有效期,默认为300s #key_prefix:缓存键前缀,默认为 view/ +路由地址 @cache.cached(timeout=100,key_prefix='index') def set_cache(): #进行测试,第一次时会执行,之后就会直接调用缓存数据 print('调动数据库') return '返回结果' #创建缓存基本函数 @cache.cached(timeout=100,key_prefix='index1') def set_cache1(): print('调用数据库') return '返回结果' #创建视图函数 @app.route('/set_cache2/') def set_cache2(): return set_cache1() #自定义缓存视图函数 @app.route('/set_cache3/') def set_cache3(): #先去缓存中查找数据 data = cache.get('data') #如果缓存中有数据,返回缓存数据 if data: print('缓存数据') return data #如果缓存中没有数据,设置新数据 data = '123456' #并在缓存中设置 cache.set('data',data,timeout=100) print('非缓存数据') return data @app.route('/clear_cache/') def clear_cache(): #指定缓存名删除 cache.delete('index') return '清除缓存' @app.route('/clear_cache_all/') def clear_cache_all(): #清除所有的缓存 cache.clear() return '清除缓存' if __name__ == '__main__': manage.run()
flask 缓存的设置及使用
最新推荐文章于 2024-06-18 09:00:00 发布