2011-03-28 10:11:19 +08:00
|
|
|
from functools import wraps
|
2015-01-28 20:35:27 +08:00
|
|
|
|
2005-10-09 08:55:08 +08:00
|
|
|
from django.middleware.cache import CacheMiddleware
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.utils.cache import add_never_cache_headers, patch_cache_control
|
2017-01-22 02:20:17 +08:00
|
|
|
from django.utils.decorators import decorator_from_middleware_with_args
|
2005-10-09 08:55:08 +08:00
|
|
|
|
2010-02-09 23:02:39 +08:00
|
|
|
|
2017-02-02 00:41:56 +08:00
|
|
|
def cache_page(timeout, *, cache=None, key_prefix=None):
|
2010-12-04 14:49:51 +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.
|
|
|
|
|
|
|
|
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
|
2014-01-26 04:54:25 +08:00
|
|
|
get_current_site().domain, for example, as that is unique across a Django
|
2010-12-04 14:49:51 +08:00
|
|
|
project.
|
|
|
|
|
|
|
|
Additionally, all headers from the response's Vary header will be taken
|
|
|
|
into account on caching -- just like the middleware does.
|
|
|
|
"""
|
2014-09-04 20:15:09 +08:00
|
|
|
return decorator_from_middleware_with_args(CacheMiddleware)(
|
2017-02-02 00:41:56 +08:00
|
|
|
cache_timeout=timeout, cache_alias=cache, key_prefix=key_prefix
|
2014-09-04 20:15:09 +08:00
|
|
|
)
|
2005-10-30 01:00:20 +08:00
|
|
|
|
|
|
|
|
2010-02-09 23:02:39 +08:00
|
|
|
def cache_control(**kwargs):
|
2005-10-30 01:00:20 +08:00
|
|
|
def _cache_controller(viewfunc):
|
2017-01-22 02:20:17 +08:00
|
|
|
@wraps(viewfunc)
|
2005-10-30 01:00:20 +08:00
|
|
|
def _cache_controlled(request, *args, **kw):
|
|
|
|
response = viewfunc(request, *args, **kw)
|
|
|
|
patch_cache_control(response, **kwargs)
|
|
|
|
return response
|
2011-05-02 00:46:02 +08:00
|
|
|
return _cache_controlled
|
2010-02-09 23:02:39 +08:00
|
|
|
return _cache_controller
|
2005-10-30 01:00:20 +08:00
|
|
|
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
def never_cache(view_func):
|
|
|
|
"""
|
2017-01-25 04:36:07 +08:00
|
|
|
Decorator that adds headers to a response so that it will never be cached.
|
2006-05-02 09:31:56 +08:00
|
|
|
"""
|
2017-01-22 02:20:17 +08:00
|
|
|
@wraps(view_func)
|
2006-05-02 09:31:56 +08:00
|
|
|
def _wrapped_view_func(request, *args, **kwargs):
|
|
|
|
response = view_func(request, *args, **kwargs)
|
|
|
|
add_never_cache_headers(response)
|
|
|
|
return response
|
2011-05-02 00:46:02 +08:00
|
|
|
return _wrapped_view_func
|