Skip to content

Instantly share code, notes, and snippets.

@dnozay
Created December 28, 2011 02:32
Show Gist options
  • Save dnozay/1525886 to your computer and use it in GitHub Desktop.
Save dnozay/1525886 to your computer and use it in GitHub Desktop.
@cache_condition, @cache_last_modified, @cache_etag
# decorators to leverage cache based on conditional view processing.
# cache_condition decorator based on django.views.decorators.http.condition
# cache_last_modified, cache_etag shortcuts.
# settings.py
# -----------
# you may or may not want this.
# CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True
MIDDLEWARE_CLASSES = (
'django.middleware.cache.UpdateCacheMiddleware', # top one.
...
)
# decorators.py
# -------------
from django.views.decorators.http import condition
from django.utils.cache import get_cache_key
from django.core.cache import cache
def cache_condition(*args, **kwargs):
def decorator(func):
def inner(request, *args, **kwargs):
cache_key = get_cache_key(request, method=request.method)
response = cache.get(cache_key)
if response is not None:
return response
# do not use FetchFromCacheMiddleware, behave the same
request._cache_update_cache = True
return func(request, *args, **kwargs)
return condition(*args, **kwargs)(inner)
return decorator
def cache_etag(etag_func):
return cache_condition(etag_func=etag_func)
def cache_last_modified(last_modified_func):
return cache_condition(last_modified_func=last_modified_func)
# views.py
# --------
# e.g.
#
# def latest_entry(request, blog_id):
# return Entry.objects.filter(blog=blog_id).latest("published").published
#
# seealso:
# https://docs.djangoproject.com/en/1.3/topics/conditional-view-processing/
@cache_last_modified(latest_entry)
def front_page(request, blog_id):
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment