使用redis做缓存主要是速度快,缓存一些不经常变化的但访问量大的页面,使用户体验更好。
安装redis数据库pip install redispip install flask-caching在你的项目创建create_app函数下初始化缓存 打开redis服务 from flask_caching import Cache # 缓存 cache = Cache() def create_app(): .... # 初始化缓存文件 cache.init_app(app=app, config={ 'CACHE_TYPE': 'redis', # 缓存类型 'CACHE_REDIS_URL': 'redis://@localhost:6379/2' # 无密码, 有密码:redis://user:password@localhost:6379/2 }) .... return app常用的
1、缓存短信验证码什么的 cache.set('code', code, timeout=180) # 设置缓存,(key,value, timeout(秒)) cache.set_many([(key, value), (key, value), ...]) # 缓存多个 cache.get(key) # 获取, cache.get_many(key, key2, ...) cache.delete(key) # 删除, cache.delete_many(key, key2, ...) cache.clear() # 清空 2、视图缓存 @app_bp.route('/', methods=['GET', 'POST'], endpoint='index') @cache.cached(timeout=10) # 视图缓存,10秒后过期 def index(): ......然后我用来缓存了验证码