diff options
Diffstat (limited to 'django/middleware/cache.py')
| -rw-r--r-- | django/middleware/cache.py | 19 |
1 files changed, 17 insertions, 2 deletions
diff --git a/django/middleware/cache.py b/django/middleware/cache.py index 80c8626db8..58800b24da 100644 --- a/django/middleware/cache.py +++ b/django/middleware/cache.py @@ -1,7 +1,6 @@ from django.conf import settings from django.core.cache import cache from django.utils.cache import get_cache_key, learn_cache_key, patch_response_headers -from django.http import HttpResponseNotModified class CacheMiddleware(object): """ @@ -10,6 +9,11 @@ class CacheMiddleware(object): Only parameter-less GET or HEAD-requests with status code 200 are cached. + If CACHE_MIDDLEWARE_ANONYMOUS_ONLY is set to True, only anonymous requests + (i.e., those node made by a logged-in user) will be cached. This is a + simple and effective way of avoiding the caching of the Django admin (and + any other user-specific content). + This middleware expects that a HEAD request is answered with a response exactly like the corresponding GET request. @@ -23,20 +27,31 @@ class CacheMiddleware(object): This middleware also sets ETag, Last-Modified, Expires and Cache-Control headers on the response object. """ - def __init__(self, cache_timeout=None, key_prefix=None): + def __init__(self, cache_timeout=None, key_prefix=None, cache_anonymous_only=None): self.cache_timeout = cache_timeout if cache_timeout is None: self.cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS self.key_prefix = key_prefix if key_prefix is None: self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX + if cache_anonymous_only is None: + self.cache_anonymous_only = getattr(settings, 'CACHE_MIDDLEWARE_ANONYMOUS_ONLY', False) + else: + self.cache_anonymous_only = cache_anonymous_only def process_request(self, request): "Checks whether the page is already cached and returns the cached version if available." + if self.cache_anonymous_only: + assert hasattr(request, 'user'), "The Django cache middleware with CACHE_MIDDLEWARE_ANONYMOUS_ONLY=True requires authentication middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.auth.middleware.AuthenticationMiddleware' before the CacheMiddleware." + if not request.method in ('GET', 'HEAD') or request.GET: request._cache_update_cache = False return None # Don't bother checking the cache. + if self.cache_anonymous_only and request.user.is_authenticated(): + request._cache_update_cache = False + return None # Don't cache requests from authenticated users. + cache_key = get_cache_key(request, self.key_prefix) if cache_key is None: request._cache_update_cache = True |
