Debian Codegraph @

django/views/decorators/http.py

raw
1 """
2 Decorators for views based on HTTP headers.
3 """
4
5 import datetime
6 from functools import wraps
7
8 from asgiref.sync import iscoroutinefunction
9
10 from django.http import HttpResponseNotAllowed
11 from django.middleware.http import ConditionalGetMiddleware
12 from django.utils import timezone
13 from django.utils.cache import get_conditional_response
14 from django.utils.decorators import decorator_from_middleware
15 from django.utils.http import http_date, quote_etag
16 from django.utils.log import log_response
17
18 conditional_page = decorator_from_middleware(ConditionalGetMiddleware)
19
20
21 def require_http_methods(request_method_list):
22 """
23 Decorator to make a view only accept particular request methods. Usage::
24
25 @require_http_methods(["GET", "POST"])
26 def my_view(request):
27 # I can assume now that only GET or POST requests make it this far
28 # ...
29
30 Note that request methods should be in uppercase.
31 """
32
33 def decorator(func):
34 if iscoroutinefunction(func):
35
36 @wraps(func)
37 async def inner(request, *args, **kwargs):
38 if request.method not in request_method_list:
39 response = HttpResponseNotAllowed(request_method_list)
40 log_response(
41 "Method Not Allowed (%s): %s",
42 request.method,
43 request.path,
44 response=response,
45 request=request,
46 )
47 return response
48 return await func(request, *args, **kwargs)
49
50 else:
51
52 @wraps(func)
53 def inner(request, *args, **kwargs):
54 if request.method not in request_method_list:
55 response = HttpResponseNotAllowed(request_method_list)
56 log_response(
57 "Method Not Allowed (%s): %s",
58 request.method,
59 request.path,
60 response=response,
61 request=request,
62 )
63 return response
64 return func(request, *args, **kwargs)
65
66 return inner
67
68 return decorator
69
70
71 require_GET = require_http_methods(["GET"])
72 require_GET.__doc__ = "Decorator to require that a view only accepts the GET method."
73
74 require_POST = require_http_methods(["POST"])
75 require_POST.__doc__ = "Decorator to require that a view only accepts the POST method."
76
77 require_safe = require_http_methods(["GET", "HEAD"])
78 require_safe.__doc__ = (
79 "Decorator to require that a view only accepts safe methods: GET and HEAD."
80 )
81
82
83 def condition(etag_func=None, last_modified_func=None):
84 """
85 Decorator to support conditional retrieval (or change) for a view
86 function.
87
88 The parameters are callables to compute the ETag and last modified time for
89 the requested resource, respectively. The callables are passed the same
90 parameters as the view itself. The ETag function should return a string (or
91 None if the resource doesn't exist), while the last_modified function
92 should return a datetime object (or None if the resource doesn't exist).
93
94 The ETag function should return a complete ETag, including quotes (e.g.
95 '"etag"'), since that's the only way to distinguish between weak and strong
96 ETags. If an unquoted ETag is returned (e.g. 'etag'), it will be converted
97 to a strong ETag by adding quotes.
98
99 This decorator will either pass control to the wrapped view function or
100 return an HTTP 304 response (unmodified) or 412 response (precondition
101 failed), depending upon the request method. In either case, the decorator
102 will add the generated ETag and Last-Modified headers to the response if
103 the headers aren't already set and if the request's method is safe.
104 """
105
106 def decorator(func):
107 def _pre_process_request(request, *args, **kwargs):
108 # Compute values (if any) for the requested resource.
109 res_last_modified = None
110 if last_modified_func:
111 if dt := last_modified_func(request, *args, **kwargs):
112 if not timezone.is_aware(dt):
113 dt = timezone.make_aware(dt, datetime.timezone.utc)
114 res_last_modified = int(dt.timestamp())
115 # The value from etag_func() could be quoted or unquoted.
116 res_etag = etag_func(request, *args, **kwargs) if etag_func else None
117 res_etag = quote_etag(res_etag) if res_etag is not None else None
118 response = get_conditional_response(
119 request,
120 etag=res_etag,
121 last_modified=res_last_modified,
122 )
123 return response, res_etag, res_last_modified
124
125 def _post_process_request(request, response, res_etag, res_last_modified):
126 # Set relevant headers on the response if they don't already exist
127 # and if the request method is safe.
128 if request.method in ("GET", "HEAD"):
129 if res_last_modified and not response.has_header("Last-Modified"):
130 response.headers["Last-Modified"] = http_date(res_last_modified)
131 if res_etag:
132 response.headers.setdefault("ETag", res_etag)
133
134 if iscoroutinefunction(func):
135
136 @wraps(func)
137 async def inner(request, *args, **kwargs):
138 response, res_etag, res_last_modified = _pre_process_request(
139 request, *args, **kwargs
140 )
141 if response is None:
142 response = await func(request, *args, **kwargs)
143 _post_process_request(request, response, res_etag, res_last_modified)
144 return response
145
146 else:
147
148 @wraps(func)
149 def inner(request, *args, **kwargs):
150 response, res_etag, res_last_modified = _pre_process_request(
151 request, *args, **kwargs
152 )
153 if response is None:
154 response = func(request, *args, **kwargs)
155 _post_process_request(request, response, res_etag, res_last_modified)
156 return response
157
158 return inner
159
160 return decorator
161
162
163 # Shortcut decorators for common cases based on ETag or Last-Modified only
164 def etag(etag_func):
165 return condition(etag_func=etag_func)
166
167
168 def last_modified(last_modified_func):
169 return condition(last_modified_func=last_modified_func)