app/django/views/decorators/cache.py
changeset 54 03e267d67478
equal deleted inserted replaced
53:57b4279d8c4e 54:03e267d67478
       
     1 """
       
     2 Decorator for views that tries getting the page from the cache and
       
     3 populates the cache if the page isn't in the cache yet.
       
     4 
       
     5 The cache is keyed by the URL and some data from the headers. Additionally
       
     6 there is the key prefix that is used to distinguish different cache areas
       
     7 in a multi-site setup. You could use the sites.get_current().domain, for
       
     8 example, as that is unique across a Django project.
       
     9 
       
    10 Additionally, all headers from the response's Vary header will be taken into
       
    11 account on caching -- just like the middleware does.
       
    12 """
       
    13 
       
    14 try:
       
    15     from functools import wraps
       
    16 except ImportError:
       
    17     from django.utils.functional import wraps  # Python 2.3, 2.4 fallback.
       
    18 
       
    19 from django.utils.decorators import decorator_from_middleware
       
    20 from django.utils.cache import patch_cache_control, add_never_cache_headers
       
    21 from django.middleware.cache import CacheMiddleware
       
    22 
       
    23 cache_page = decorator_from_middleware(CacheMiddleware)
       
    24 
       
    25 def cache_control(**kwargs):
       
    26 
       
    27     def _cache_controller(viewfunc):
       
    28 
       
    29         def _cache_controlled(request, *args, **kw):
       
    30             response = viewfunc(request, *args, **kw)
       
    31             patch_cache_control(response, **kwargs)
       
    32             return response
       
    33 
       
    34         return wraps(viewfunc)(_cache_controlled)
       
    35 
       
    36     return _cache_controller
       
    37 
       
    38 def never_cache(view_func):
       
    39     """
       
    40     Decorator that adds headers to a response so that it will
       
    41     never be cached.
       
    42     """
       
    43     def _wrapped_view_func(request, *args, **kwargs):
       
    44         response = view_func(request, *args, **kwargs)
       
    45         add_never_cache_headers(response)
       
    46         return response
       
    47     return wraps(view_func)(_wrapped_view_func)