2005-10-09 08:55:08 +08:00
|
|
|
"""
|
|
|
|
Decorator for views that tries getting the page from the cache and
|
|
|
|
populates the cache if the page isn't in the cache yet.
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2005-10-09 08:55:08 +08:00
|
|
|
The cache is keyed by the URL and some data from the headers. Additionally
|
|
|
|
there is the key prefix that is used to distinguish different cache areas
|
|
|
|
in a multi-site setup. You could use the sites.get_current().domain, for
|
|
|
|
example, as that is unique across a Django project.
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2005-10-09 08:55:08 +08:00
|
|
|
Additionally, all headers from the response's Vary header will be taken into
|
|
|
|
account on caching -- just like the middleware does.
|
|
|
|
"""
|
|
|
|
|
2008-02-25 14:02:35 +08:00
|
|
|
try:
|
|
|
|
from functools import wraps
|
|
|
|
except ImportError:
|
|
|
|
from django.utils.functional import wraps # Python 2.3, 2.4 fallback.
|
|
|
|
|
2009-09-22 06:31:51 +08:00
|
|
|
from django.utils.decorators import decorator_from_middleware_with_args, auto_adapt_to_methods
|
2006-05-02 09:31:56 +08:00
|
|
|
from django.utils.cache import patch_cache_control, add_never_cache_headers
|
2005-10-09 08:55:08 +08:00
|
|
|
from django.middleware.cache import CacheMiddleware
|
|
|
|
|
2009-09-22 06:31:51 +08:00
|
|
|
def cache_page(*args, **kwargs):
|
|
|
|
# We need backwards compatibility with code which spells it this way:
|
|
|
|
# def my_view(): pass
|
|
|
|
# my_view = cache_page(123, my_view)
|
|
|
|
# and this way:
|
|
|
|
# my_view = cache_page(123)(my_view)
|
|
|
|
timeout = args[0]
|
|
|
|
if len(args) > 1:
|
|
|
|
fn = args[1]
|
|
|
|
return decorator_from_middleware_with_args(CacheMiddleware)(timeout)(fn)
|
|
|
|
else:
|
|
|
|
return decorator_from_middleware_with_args(CacheMiddleware)(timeout)
|
2005-10-30 01:00:20 +08:00
|
|
|
|
|
|
|
def cache_control(**kwargs):
|
|
|
|
|
|
|
|
def _cache_controller(viewfunc):
|
|
|
|
|
|
|
|
def _cache_controlled(request, *args, **kw):
|
|
|
|
response = viewfunc(request, *args, **kw)
|
|
|
|
patch_cache_control(response, **kwargs)
|
|
|
|
return response
|
|
|
|
|
2008-02-25 14:02:35 +08:00
|
|
|
return wraps(viewfunc)(_cache_controlled)
|
2005-10-30 01:00:20 +08:00
|
|
|
|
2009-09-22 06:31:51 +08:00
|
|
|
return auto_adapt_to_methods(_cache_controller)
|
2005-10-30 01:00:20 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
def never_cache(view_func):
|
|
|
|
"""
|
|
|
|
Decorator that adds headers to a response so that it will
|
|
|
|
never be cached.
|
|
|
|
"""
|
|
|
|
def _wrapped_view_func(request, *args, **kwargs):
|
|
|
|
response = view_func(request, *args, **kwargs)
|
|
|
|
add_never_cache_headers(response)
|
|
|
|
return response
|
2008-02-25 14:02:35 +08:00
|
|
|
return wraps(view_func)(_wrapped_view_func)
|
2009-09-22 06:31:51 +08:00
|
|
|
never_cache = auto_adapt_to_methods(never_cache)
|