python - Expire a view-cache in Django? -
the @cache_page decorator
awesome. blog keep page in cache until comments on post. sounds great idea people comment keeping pages in memcached while nobody comments great. i'm thinking must have had problem before? , different caching per url.
so solution i'm thinking of is:
@cache_page( 60 * 15, "blog" ); def blog( request ) ...
and i'd keep list of cache keys used blog view , have way of expire "blog" cache space. i'm not super experienced django i'm wondering if knows better way of doing this?
here's solution wrote you're talking on of own projects:
def expire_view_cache(view_name, args=[], namespace=none, key_prefix=none): """ function allows invalidate view-level cache. view_name: view function wish invalidate or it's named url pattern args: arguments passed view function namepace: optioal, if application namespace needed key prefix: @cache_page decorator function (if any) """ django.core.urlresolvers import reverse django.http import httprequest django.utils.cache import get_cache_key django.core.cache import cache # create fake request object request = httprequest() # loookup request path: if namespace: view_name = namespace + ":" + view_name request.path = reverse(view_name, args=args) # cache key, expire if cached item exists: key = get_cache_key(request, key_prefix=key_prefix) if key: if cache.get(key): # delete cache entry. # # note there possible race condition here, # process / thread may have refreshed cache between # call cache.get() above, , cache.set(key, none) # below. may lead unexpected performance problems under # severe load. cache.set(key, none, 0) return true return false
django keys these caches of view request, creates fake request object cached view, uses fetch cache key, expires it.
to use in way you're talking about, try like:
from django.db.models.signals import post_save blog.models import entry def invalidate_blog_index(sender, **kwargs): expire_view_cache("blog") post_save.connect(invalidate_portfolio_index, sender=entry)
so basically, when ever blog entry object saved, invalidate_blog_index called , cached view expired. nb: haven't tested extensively, it's worked fine me far.
Comments
Post a Comment