Skip to content

Instantly share code, notes, and snippets.

@kblum
Created January 10, 2012 22:00
Show Gist options
  • Save kblum/1591459 to your computer and use it in GitHub Desktop.
Save kblum/1591459 to your computer and use it in GitHub Desktop.
Django cache page decorator for class-based view
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
def CachePage(cls=None, **cache_kwargs):
"""
Apply the ``cache_page`` decorator to all the handlers in a class-based
view that delegate to the ``dispatch`` method.
Optional arguments
``timeout`` -- Cache timeout, in seconds.``
Usage (without timeout parameter):
@CachePage
class MyView (TemplateView):
...
Usage (with 5 minute timeout):
@CachePage(60*5)
class MyView(TemplateView):
...
Based on login required decorator: http://djangosnippets.org/snippets/2495/
"""
if cls is not None:
# Check that the View class is a class-based view. This can either be
# done by checking inheritance from django.views.generic.View, or by
# checking that the ViewClass has a ``dispatch`` method.
if not hasattr(cls, 'dispatch'):
raise TypeError(('View class is not valid: %r. Class-based views '
'must have a dispatch method.') % cls)
timeout = None
if cache_kwargs.has_key('timeout'):
timeout = cache_kwargs.pop('timeout')
original = cls.dispatch
if timeout:
modified = method_decorator(cache_page(timeout, **cache_kwargs))(original)
else:
modified = method_decorator(cache_page(**cache_kwargs))(original)
cls.dispatch = modified
return cls
else:
# If ViewClass is None, then this was applied as a decorator with
# parameters. An inner decorator will be used to capture the ViewClass,
# and return the actual decorator method.
def inner_decorator(inner_cls):
return CachePage(inner_cls, **cache_kwargs)
return inner_decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment