- 28
- 11月
Flask-Cache是一个提供简便缓存支持的Flask扩展。支持memcached, gaememcached,filesystem,simple等缓存类型。
2 设置
缓存通过 Cache 实例进行管理:
from flask import Flask
from flask.ext.cache import Cache
app = Flask(__name__)
# Check Configuring Flask-Cache section for more details
cache = Cache(app,config={'CACHE_TYPE': 'simple'})
你也可以在配置之后通过 init_app 方法设置你的 Cache 实例:
cache = Cache(config={'CACHE_TYPE': 'simple'})
app = Flask(__name__)
cache.init_app(app)
你也可以提供一个配置字典,如果存在多个 Cache 实例使用不同的缓存后端 ,这很有用:
#: Method A: During instantiation of class
cache = Cache(config={'CACHE_TYPE': 'simple'})
#: Method B: During init_app call
cache.init_app(app, config={'CACHE_TYPE': 'simple'})
0.7版本新增。
3 缓存视图函数
要缓存视图函数你可以使用 cached 装饰器。这个装饰器将使用 request.path 作为默认的 cache_key.:
@cache.cached(timeout=50)
def index():
return render_template('index.html')
cached 装饰器有一个叫 unless 的可选参数。这个参数接受一个返回 True 或 False 的可调用对象。如果 unless 返回 True ,则会 完全绕过缓存机制。
4 缓存其他函数
使用相同的 cached 装饰器你能够缓存其他非视图相关函数的运行结果。唯一 的规定是替换 key_prefix ,否则它会使用 request.path cache_key:
@cache.cached(timeout=50, key_prefix='all_comments')
def get_all_comments():
comments = do_serious_dbio()
return [x.author for x in comments]
cached_comments = get_all_comments()
5 清除缓存
参照 clear() 。
这是一个清空应用程序缓存的样本脚本:
from flask.ext.cache import Cache
from yourapp import app, your_cache_config
cache = Cache()
def main():
cache.init_app(app, config=your_cache_config)
with app.app_context():
cache.clear()
if __name__ == '__main__':
main()
警告
一些缓存后端实现方式不支持完全的清除缓存。而且,如果你不使用 key_prefix,一些实现方式(比如Redis)会清除整个数据库。确保你在 你的缓存数据库中没有存储其他数据。
粤公网安备 44030602003142号