设置失效时间,单位秒
cache = Cache(app,config={'CACHE_TYPE': 'simple','CACHE_DEFAULT_TIMEOUT': 600})
代码中添加缓存
def get_nav_list(username, timeout=600):
u'''
通过用户名获取导航条
'''
key = "cache_nav_%s" % username
navs = cache.get(key)
if navs is None:
q_navs = Nav.query.filter_by(status=1,owner_id=get_userid(username)).order_by(asc('rank'))
navs = None if q_navs.count()==0 else q_navs.all()
cache.set(key, navs, timeout=timeout)
return navs
模板中添加缓存
{% cache 60*10,'template_article_%s' % art.id %}
<article class="post type-post status-publish format-standard hentry category-technology">
...
</article>
{% endcache %}
模板缓存时,缓存的部分会生成html字符串并存储在内存中,每次访问页面时不用解析响应的模板内容,从而提高访问效率
更新内容时,清空缓存
def delete_caches(self,id):
u'''
delete Article's caches
'''
from flask.ext.cache import make_template_fragment_key
template_key = make_template_fragment_key("template_article_%s" % id)
caches_key = "cache_article_%s" % id
cache.delete(template_key)
cache.delete(caches_key)