Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/django/views/decorators/cache.py: 33%

26 statements  

« prev     ^ index     » next       coverage.py v6.4.4, created at 2023-07-17 14:22 -0600

1from functools import wraps 

2 

3from django.middleware.cache import CacheMiddleware 

4from django.utils.cache import add_never_cache_headers, patch_cache_control 

5from django.utils.decorators import decorator_from_middleware_with_args 

6 

7 

8def cache_page(timeout, *, cache=None, key_prefix=None): 

9 """ 

10 Decorator for views that tries getting the page from the cache and 

11 populates the cache if the page isn't in the cache yet. 

12 

13 The cache is keyed by the URL and some data from the headers. 

14 Additionally there is the key prefix that is used to distinguish different 

15 cache areas in a multi-site setup. You could use the 

16 get_current_site().domain, for example, as that is unique across a Django 

17 project. 

18 

19 Additionally, all headers from the response's Vary header will be taken 

20 into account on caching -- just like the middleware does. 

21 """ 

22 return decorator_from_middleware_with_args(CacheMiddleware)( 

23 page_timeout=timeout, 

24 cache_alias=cache, 

25 key_prefix=key_prefix, 

26 ) 

27 

28 

29def cache_control(**kwargs): 

30 def _cache_controller(viewfunc): 

31 @wraps(viewfunc) 

32 def _cache_controlled(request, *args, **kw): 

33 # Ensure argument looks like a request. 

34 if not hasattr(request, "META"): 

35 raise TypeError( 

36 "cache_control didn't receive an HttpRequest. If you are " 

37 "decorating a classmethod, be sure to use " 

38 "@method_decorator." 

39 ) 

40 response = viewfunc(request, *args, **kw) 

41 patch_cache_control(response, **kwargs) 

42 return response 

43 

44 return _cache_controlled 

45 

46 return _cache_controller 

47 

48 

49def never_cache(view_func): 

50 """ 

51 Decorator that adds headers to a response so that it will never be cached. 

52 """ 

53 

54 @wraps(view_func) 

55 def _wrapped_view_func(request, *args, **kwargs): 

56 # Ensure argument looks like a request. 

57 if not hasattr(request, "META"): 

58 raise TypeError( 

59 "never_cache didn't receive an HttpRequest. If you are " 

60 "decorating a classmethod, be sure to use @method_decorator." 

61 ) 

62 response = view_func(request, *args, **kwargs) 

63 add_never_cache_headers(response) 

64 return response 

65 

66 return _wrapped_view_func