【问题标题】:Removing specific items from Django's cache?从 Django 的缓存中删除特定项目?
【发布时间】:2010-10-17 18:34:48
【问题描述】:

我正在使用以memcached 作为后端的站点范围缓存。当底层数据库对象更改时,我想使缓存中的页面无效。

如果页面名称更改,那么我将使整个缓存无效(因为它会影响每个页面上的导航。笨拙但足以满足我的需求。

如果只是页面内容发生变化,那么我想使该页面的缓存无效。

有没有简单的方法来做到这一点?

【问题讨论】:

    标签: python django caching memcached


    【解决方案1】:

    我没有用 Django 做很多缓存,但我想你在这里想要的是signals

    您可以在底层对象上设置post_save 信号,并让回调函数使缓存中的该页面无效。

    from django.core.signals import post_save
    from django.core.cache import cache
    
    def invalidate_cache(sender, **kwargs):
        # invalidate cache
        cache.delete(sender.get_absolute_url()) # or any other pertinent keys
    
    post_save.connect(invalidate_cache, sender=UnderlyingModel)
    

    这应该会在更新时从缓存中正确删除该项目。

    【讨论】:

    • 我不知道 cache.delete sender.get_absolute_url() 是否为我提供了正确的缓存键?我看不到任何关于站点范围的缓存如何生成密钥的文档。
    • "默认情况下,Django 的缓存系统使用请求的路径(例如,"/stories/2005/jun/23/bank_robbed/")创建其缓存键。" (docs.djangoproject.com/en/dev/topics/cache)
    【解决方案2】:

    tghw 的解决方案实际上不起作用,因为缓存键不是绝对路径。密钥是根据绝对路径和 HTTP 标头计算得出的。示例见this question

    【讨论】:

      猜你喜欢
      • 2010-10-16
      • 2012-09-16
      • 2018-03-07
      • 1970-01-01
      • 1970-01-01
      • 2023-01-09
      • 2012-02-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多