You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

cache.py 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. from functools import wraps
  2. from django.middleware.cache import CacheMiddleware
  3. from django.utils.cache import add_never_cache_headers, patch_cache_control
  4. from django.utils.decorators import decorator_from_middleware_with_args
  5. def cache_page(timeout, *, cache=None, key_prefix=None):
  6. """
  7. Decorator for views that tries getting the page from the cache and
  8. populates the cache if the page isn't in the cache yet.
  9. The cache is keyed by the URL and some data from the headers.
  10. Additionally there is the key prefix that is used to distinguish different
  11. cache areas in a multi-site setup. You could use the
  12. get_current_site().domain, for example, as that is unique across a Django
  13. project.
  14. Additionally, all headers from the response's Vary header will be taken
  15. into account on caching -- just like the middleware does.
  16. """
  17. return decorator_from_middleware_with_args(CacheMiddleware)(
  18. cache_timeout=timeout, cache_alias=cache, key_prefix=key_prefix
  19. )
  20. def cache_control(**kwargs):
  21. def _cache_controller(viewfunc):
  22. @wraps(viewfunc)
  23. def _cache_controlled(request, *args, **kw):
  24. response = viewfunc(request, *args, **kw)
  25. patch_cache_control(response, **kwargs)
  26. return response
  27. return _cache_controlled
  28. return _cache_controller
  29. def never_cache(view_func):
  30. """
  31. Decorator that adds headers to a response so that it will never be cached.
  32. """
  33. @wraps(view_func)
  34. def _wrapped_view_func(request, *args, **kwargs):
  35. response = view_func(request, *args, **kwargs)
  36. add_never_cache_headers(response)
  37. return response
  38. return _wrapped_view_func