Created
January 10, 2012 22:00
-
-
Save kblum/1591459 to your computer and use it in GitHub Desktop.
Django cache page decorator for class-based view
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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