本文介绍了递归地使Django缓存中的路径生效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我从Django缓存中删除单个路径,如下所示:

I am deleting a single path from the Django cache like this:

from models                   import Graph
from django.http              import HttpRequest
from django.utils.cache       import get_cache_key
from django.db.models.signals import post_save
from django.core.cache        import cache

def expire_page(path):
    request      = HttpRequest()
    request.path = path
    key          = get_cache_key(request)
    if cache.has_key(key):
        cache.delete(key)

def invalidate_cache(sender, instance, **kwargs):
    expire_page(instance.get_absolute_url())

post_save.connect(invalidate_cache, sender = Graph)

这是有效的 - 但是有没有递归删除的方法?我的路径如下所示:

This works - but is there a way to delete recursively? My paths look like this:

/graph/123
/graph/123/2009-08-01/2009-10-21


每当保存ID为123的图形,两个路径的缓存都需要无效。可以这样做吗?

Whenever the graph with id "123" is saved, the cache for both paths needs to be invalidated. Can this be done?

推荐答案

您可能需要考虑采用代际缓存策略,似乎会适合您的试图完成。在您提供的代码中,您将为每个绝对URL存储代号。因此,例如,您将初始化/ graph / 123以生成一个,则其缓存键将成为/ GENERATION / 1 / graph / 123。当您想要使该绝对URL的缓存到期时,您可以增加其生成值(在这种情况下为两个)。这样,下次有人去查找/ graph / 123时,缓存键将变为/ GENERATION / 2 / graph / 123。这也解决了所有子页面到期的问题,因为它们应该引用与/ graph / 123相同的缓存密钥。

You might want to consider employing a generational caching strategy, it seems like it would fit what you are trying to accomplish. In the code that you have provided, you would store a "generation" number for each absolute url. So for example you would initialize the "/graph/123" to have a generation of one, then its cache key would become something like "/GENERATION/1/graph/123". When you want to expire the cache for that absolute url you increment its generation value (to two in this case). That way, the next time someone goes to look up "/graph/123" the cache key becomes "/GENERATION/2/graph/123". This also solves the issue of expiring all the sub pages since they should be referring to the same cache key as "/graph/123".

它有点棘手的理解起初,但它是一个非常优雅的缓存策略,如果正确完成意味着您不必从缓存中实际删除任何内容。有关更多信息,请参阅,它的Rails,但概念是一样的,不管语言。

Its a bit tricky to understand at first but it is a really elegant caching strategy which if done correctly means you never have to actually delete anything from cache. For more information here is a presentation on generational caching, its for Rails but the concept is the same, regardless of language.

这篇关于递归地使Django缓存中的路径生效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 14:28