拉齐Django片段缓存甜蜜
django-cache-sweeper的Python项目详细描述
通过使用每模型版本标记作为缓存密钥的前缀来分段缓存失效。版本标记可以是内部memcached计数器,也可以是模型中的时间戳属性,例如updated_at。
安装
使用pip或python setup.py install安装并将“cachesweeper”添加到您的设置中。已安装的应用程序
后置保存缓存清理程序
一个示例设置;一篇文章有许多注释,每个注释都被缓存,一次投票将使注释的特定缓存片段以及整个文章的页面失效。
模板片段缓存
{%cachesweeper%}以django orm模型为第一个参数,过期时间为第二个参数,以下任何参数都用于构造缓存键的其余部分
{% load markup %} {% load cachesweeper_tags %} {% cachesweeper comment 500 "comment.xml" %} <p> <strong>{{comment.user}}</strong> said at {{comment.created_at}}:<br/> {{comment.content|markdown}} <br/> <a href={% url like article_id=article.pk,comment_id=comment.pk %}>Like ({{comment.likes.count}})</a> <a href={% url dislike article_id=article.pk,comment_id=comment.pk %}>Dislike ({{comment.dislikes.count}})</a> </p> {% endcachesweeper %}
在模型更改时使片段无效
在post_save中,使给定模型的缓存失效。有两个选项,要么让memcached为每个模型保留一个内部版本计数器,要么使用关键字来对缓存进行版本控制。
from cachesweeper.utils import invalidate_cache_for # using Memcached's internal counter def invalidate_vote_cache(sender, **kwargs): vote = kwargs.get('instance') invalidate_cache_for(vote.comment) post_save.connect(invalidate_vote_cache, sender=Vote) # using a model's attribute def invalidate_article_cache(sender, **kwargs): article = kwargs.get('instance') invalidate_cache_for(article, using='updated_at') post_save.connect(invalidate_article_cache, sender=Article)