Flask-Cache

说明

数据库的速度通常会是影响一个应用的瓶颈因素,因此未来提高效率,尽可能要减少数据库的访问。把经常使用的数据缓存起来,使用时先从缓存中查找,而不是每次都访问数据库。flask-cache,专门负责数据缓存的扩展库

安装

  • pip install flask-cache

文档

使用

  • 配置:
from flask_cache import Cache

# 配置缓存类型
app.config['CACHE_TYPE'] = 'redis'

# 配置redis主机
app.config['CACHE_REDIS_HOST'] = '127.0.0.1'

# 配置redis端口
app.config['CACHE_REDIS_PORT'] = 6379

# 配置redis数据库
app.config['CACHE_REDIS_DB'] = 1

# 创建缓存对象
cache = Cache(app, with_jinja2_ext=False)
  • 缓存视图函数
@app.route('/')
# timeout:缓存有效期,传递一个整数
# key_prefix:缓存的键前缀,默认:flask_cache_view/路由地址
# unless:传递一个函数,该函数返回True时缓存失效(即使在有效期内)
@cache.cached(timeout=100, key_prefix='index')
def index():
    print('查询数据库')
    return '数据缓存'
  • 清除缓存
@app.route('/clear/')
def clear():
    # 清除指定缓存
    cache.delete('index')
    # 清除所有缓存
    cache.clear()
    return '缓存已清除'
  • 缓存普通函数
# 这里最好设置key_prefix,否则多个地方调用改方法会被缓存多次
@cache.cached(timeout=100, key_prefix='user_data')
def get_data():
    print('查询数据库,耗时10S')
    return 'Hello world!'

@app.route('/user1/')
def user1():
    return get_data()

@app.route('/user2/')
def user2():
    return get_data()
  • 自定义缓存
@app.route('/test/')
def test():
    # 先从缓存中获取数据
    data = cache.get('test_data')
    if data:
        return data
    else:
        print('查询数据库')
        data = '查询得到的数据'
        # 缓存起来
        cache.set('test_data', data, timeout=100)
        return data

results matching ""

    No results matching ""