Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@krallin
Forked from dpnova/gist:1223933
Last active December 30, 2015 15:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krallin/7849193 to your computer and use it in GitHub Desktop.
Save krallin/7849193 to your computer and use it in GitHub Desktop.
def expire_view_cache(view_name, args=None, kwargs=None, namespace=None, key_prefix=None, method="GET"):
"""
This function allows you to invalidate any view-level cache.
view_name: view function you wish to invalidate or it's named url pattern
args: any arguments passed to the view function
namepace: optioal, if an application namespace is needed
key prefix: for the @cache_page decorator for the function (if any)
from: http://stackoverflow.com/questions/2268417/expire-a-view-cache-in-django
added: method to request to get the key generating properly
"""
from django.core.urlresolvers import reverse
from django.http import HttpRequest
from django.utils.cache import get_cache_key
from django.core.cache import cache
from django.conf import settings
if args is None:
args = []
if kwargs is None:
kwargs = {}
# create a fake request object
request = HttpRequest()
request.method = method
if settings.USE_I18N:
request.LANGUAGE_CODE = settings.LANGUAGE_CODE
# Loookup the request path:
if namespace:
view_name = namespace + ":" + view_name
request.path = reverse(view_name, args=args, kwargs=kwargs)
# get cache key, expire if the cached item exists:
key = get_cache_key(request, key_prefix=key_prefix)
if key:
if cache.get(key):
cache.set(key, None, 0)
return True
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment