今天给大家说一说flask清除缓存的方法,话不多说直接上代码:
第三方扩展库:flask-cache
安装代码:
pip install flask-cache
IDE中配置代码,这里使用的是Pycharm
from flask_cache import Cache # 配置 # 缓存类型 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('/select/')
@cache.cached(timeout=100,key_prefix='select')
# timeout:指定缓存有效期,默认300s
# key_prefix:缓存键前缀,默认:view/ + 路由地址
def select():
students=Student.query.all()
print('读取数据')
return ','.join(s.name for s in students)缓存普通函数
# 缓存普通函数,key_prefix必须指定
@cache.cached(timeout=100, key_prefix='common')
def common():
print('查询数据库')
return '返回的数据'
@app.route('/hello/')
def hello():
return common()清除缓存
@app.route('/clear/')
def clear():
# 指定删除
# cache.delete('index')
# 全部清空
cache.clear()
return '缓存已清除'自定义缓存
@app.route('/zidingyi/')
def zidingyi():
# 先从缓存中获取
data = cache.get('zidingyi_data')
if data:
return data
# 没有缓存数据
print('从数据库中获取数据')
data = '123456'
# 缓存数据
cache.set('zidingyi_data', data, timeout=100)
return data整体代码
from flask import Flask
from flask_script import Manager
from flask_cache import Cache
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate,MigrateCommand
import os
app=Flask(__name__)
manager=Manager(app)
db=SQLAlchemy(app)
migrate=Migrate(app,db)
manager.add_command('db',MigrateCommand)
app.config['DEBUG']=True
#配置数据库
base_dir=os.path.dirname(__file__)
database_uri='sqlite:///' + os.path.join(base_dir,'data.sqlite')
app.config['SQLALCHEMY_DATABASE_URI']=database_uri
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
#配置redis
#缓存类型
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
class Student (db.Model):
id=db.Column(db.Integer,primary_key=True)
name=db.Column(db.String(20),unique=True)
#创建对象
cache=Cache(app,with_jinja2_ext=False)
#缓存视图函数
@app.route('/')
@cache.cached(key_prefix='index')
def index():
return '数据缓存'
@app.route('/add/')
# @cache.cached(timeout=100)
def add():
lt1=Student(name='liangliang')
lt2=Student(name='zhaozhao')
lt3=Student(name='da peng')
db.session.add_all([lt1,lt2,lt3])
db.session.commit()
from flask_sqlalchemy import get_debug_queries
queries = get_debug_queries()
for q in queries:
print(q)
# print('读取数据库')
return '数据已添加'
@app.route('/select/')
@cache.cached(timeout=100,key_prefix='select')
def select():
students=Student.query.all()
print('读取数据')
return ','.join(s.name for s in students)
@app.route('/clear/')
def clear():
#指定删除
cache.delete('index')
#全部清空
cache.clear()
return '缓存已删除'
if __name__=='__main__':
manager.run()好啦,以上便是关于flask清除缓存,详细说明的全部内容,更多内容干货可关注慕课网~
随时随地看视频