| 1 |
import logging |
| 2 |
|
| 3 |
from asgiref.sync import iscoroutinefunction, markcoroutinefunction |
| 4 |
|
| 5 |
from django.core.exceptions import ImproperlyConfigured |
| 6 |
from django.http import ( |
| 7 |
HttpResponse, |
| 8 |
HttpResponseGone, |
| 9 |
HttpResponseNotAllowed, |
| 10 |
HttpResponsePermanentRedirect, |
| 11 |
HttpResponseRedirect, |
| 12 |
) |
| 13 |
from django.template.response import TemplateResponse |
| 14 |
from django.urls import reverse |
| 15 |
from django.utils.decorators import classonlymethod |
| 16 |
from django.utils.functional import classproperty |
| 17 |
from django.utils.log import log_response |
| 18 |
|
| 19 |
logger = logging.getLogger("django.request") |
| 20 |
|
| 21 |
|
| 22 |
class ContextMixin: |
| 23 |
""" |
| 24 |
A default context mixin that passes the keyword arguments received by |
| 25 |
get_context_data() as the template context. |
| 26 |
""" |
| 27 |
|
| 28 |
extra_context = None |
| 29 |
|
| 30 |
def get_context_data(self, **kwargs): |
| 31 |
kwargs.setdefault("view", self) |
| 32 |
if self.extra_context is not None: |
| 33 |
kwargs.update(self.extra_context) |
| 34 |
return kwargs |
| 35 |
|
| 36 |
|
| 37 |
class View: |
| 38 |
""" |
| 39 |
Intentionally simple parent class for all views. Only implements |
| 40 |
dispatch-by-method and simple sanity checking. |
| 41 |
""" |
| 42 |
|
| 43 |
http_method_names = [ |
| 44 |
"get", |
| 45 |
"post", |
| 46 |
"put", |
| 47 |
"patch", |
| 48 |
"delete", |
| 49 |
"head", |
| 50 |
"options", |
| 51 |
"trace", |
| 52 |
] |
| 53 |
|
| 54 |
def __init__(self, **kwargs): |
| 55 |
""" |
| 56 |
Constructor. Called in the URLconf; can contain helpful extra |
| 57 |
keyword arguments, and other things. |
| 58 |
""" |
| 59 |
# Go through keyword arguments, and either save their values to our |
| 60 |
# instance, or raise an error. |
| 61 |
for key, value in kwargs.items(): |
| 62 |
setattr(self, key, value) |
| 63 |
|
| 64 |
@classproperty |
| 65 |
def view_is_async(cls): |
| 66 |
handlers = [ |
| 67 |
getattr(cls, method) |
| 68 |
for method in cls.http_method_names |
| 69 |
if (method != "options" and hasattr(cls, method)) |
| 70 |
] |
| 71 |
if not handlers: |
| 72 |
return False |
| 73 |
is_async = iscoroutinefunction(handlers[0]) |
| 74 |
if not all(iscoroutinefunction(h) == is_async for h in handlers[1:]): |
| 75 |
raise ImproperlyConfigured( |
| 76 |
f"{cls.__qualname__} HTTP handlers must either be all sync or all " |
| 77 |
"async." |
| 78 |
) |
| 79 |
return is_async |
| 80 |
|
| 81 |
@classonlymethod |
| 82 |
def as_view(cls, **initkwargs): |
| 83 |
"""Main entry point for a request-response process.""" |
| 84 |
for key in initkwargs: |
| 85 |
if key in cls.http_method_names: |
| 86 |
raise TypeError( |
| 87 |
"The method name %s is not accepted as a keyword argument " |
| 88 |
"to %s()." % (key, cls.__name__) |
| 89 |
) |
| 90 |
if not hasattr(cls, key): |
| 91 |
raise TypeError( |
| 92 |
"%s() received an invalid keyword %r. as_view " |
| 93 |
"only accepts arguments that are already " |
| 94 |
"attributes of the class." % (cls.__name__, key) |
| 95 |
) |
| 96 |
|
| 97 |
def view(request, *args, **kwargs): |
| 98 |
self = cls(**initkwargs) |
| 99 |
self.setup(request, *args, **kwargs) |
| 100 |
if not hasattr(self, "request"): |
| 101 |
raise AttributeError( |
| 102 |
"%s instance has no 'request' attribute. Did you override " |
| 103 |
"setup() and forget to call super()?" % cls.__name__ |
| 104 |
) |
| 105 |
return self.dispatch(request, *args, **kwargs) |
| 106 |
|
| 107 |
view.view_class = cls |
| 108 |
view.view_initkwargs = initkwargs |
| 109 |
|
| 110 |
# __name__ and __qualname__ are intentionally left unchanged as |
| 111 |
# view_class should be used to robustly determine the name of the view |
| 112 |
# instead. |
| 113 |
view.__doc__ = cls.__doc__ |
| 114 |
view.__module__ = cls.__module__ |
| 115 |
view.__annotations__ = cls.dispatch.__annotations__ |
| 116 |
# Copy possible attributes set by decorators, e.g. @csrf_exempt, from |
| 117 |
# the dispatch method. |
| 118 |
view.__dict__.update(cls.dispatch.__dict__) |
| 119 |
|
| 120 |
# Mark the callback if the view class is async. |
| 121 |
if cls.view_is_async: |
| 122 |
markcoroutinefunction(view) |
| 123 |
|
| 124 |
return view |
| 125 |
|
| 126 |
def setup(self, request, *args, **kwargs): |
| 127 |
"""Initialize attributes shared by all view methods.""" |
| 128 |
if hasattr(self, "get") and not hasattr(self, "head"): |
| 129 |
self.head = self.get |
| 130 |
self.request = request |
| 131 |
self.args = args |
| 132 |
self.kwargs = kwargs |
| 133 |
|
| 134 |
def dispatch(self, request, *args, **kwargs): |
| 135 |
# Try to dispatch to the right method; if a method doesn't exist, |
| 136 |
# defer to the error handler. Also defer to the error handler if the |
| 137 |
# request method isn't on the approved list. |
| 138 |
if request.method.lower() in self.http_method_names: |
| 139 |
handler = getattr( |
| 140 |
self, request.method.lower(), self.http_method_not_allowed |
| 141 |
) |
| 142 |
else: |
| 143 |
handler = self.http_method_not_allowed |
| 144 |
return handler(request, *args, **kwargs) |
| 145 |
|
| 146 |
def http_method_not_allowed(self, request, *args, **kwargs): |
| 147 |
response = HttpResponseNotAllowed(self._allowed_methods()) |
| 148 |
log_response( |
| 149 |
"Method Not Allowed (%s): %s", |
| 150 |
request.method, |
| 151 |
request.path, |
| 152 |
response=response, |
| 153 |
request=request, |
| 154 |
) |
| 155 |
|
| 156 |
if self.view_is_async: |
| 157 |
|
| 158 |
async def func(): |
| 159 |
return response |
| 160 |
|
| 161 |
return func() |
| 162 |
else: |
| 163 |
return response |
| 164 |
|
| 165 |
def options(self, request, *args, **kwargs): |
| 166 |
"""Handle responding to requests for the OPTIONS HTTP verb.""" |
| 167 |
response = HttpResponse() |
| 168 |
response.headers["Allow"] = ", ".join(self._allowed_methods()) |
| 169 |
response.headers["Content-Length"] = "0" |
| 170 |
|
| 171 |
if self.view_is_async: |
| 172 |
|
| 173 |
async def func(): |
| 174 |
return response |
| 175 |
|
| 176 |
return func() |
| 177 |
else: |
| 178 |
return response |
| 179 |
|
| 180 |
def _allowed_methods(self): |
| 181 |
return [m.upper() for m in self.http_method_names if hasattr(self, m)] |
| 182 |
|
| 183 |
|
| 184 |
class TemplateResponseMixin: |
| 185 |
"""A mixin that can be used to render a template.""" |
| 186 |
|
| 187 |
template_name = None |
| 188 |
template_engine = None |
| 189 |
response_class = TemplateResponse |
| 190 |
content_type = None |
| 191 |
|
| 192 |
def render_to_response(self, context, **response_kwargs): |
| 193 |
""" |
| 194 |
Return a response, using the `response_class` for this view, with a |
| 195 |
template rendered with the given context. |
| 196 |
|
| 197 |
Pass response_kwargs to the constructor of the response class. |
| 198 |
""" |
| 199 |
response_kwargs.setdefault("content_type", self.content_type) |
| 200 |
return self.response_class( |
| 201 |
request=self.request, |
| 202 |
template=self.get_template_names(), |
| 203 |
context=context, |
| 204 |
using=self.template_engine, |
| 205 |
**response_kwargs, |
| 206 |
) |
| 207 |
|
| 208 |
def get_template_names(self): |
| 209 |
""" |
| 210 |
Return a list of template names to be used for the request. Must return |
| 211 |
a list. May not be called if render_to_response() is overridden. |
| 212 |
""" |
| 213 |
if self.template_name is None: |
| 214 |
raise ImproperlyConfigured( |
| 215 |
"TemplateResponseMixin requires either a definition of " |
| 216 |
"'template_name' or an implementation of 'get_template_names()'" |
| 217 |
) |
| 218 |
else: |
| 219 |
return [self.template_name] |
| 220 |
|
| 221 |
|
| 222 |
class TemplateView(TemplateResponseMixin, ContextMixin, View): |
| 223 |
""" |
| 224 |
Render a template. Pass keyword arguments from the URLconf to the context. |
| 225 |
""" |
| 226 |
|
| 227 |
def get(self, request, *args, **kwargs): |
| 228 |
context = self.get_context_data(**kwargs) |
| 229 |
return self.render_to_response(context) |
| 230 |
|
| 231 |
|
| 232 |
class RedirectView(View): |
| 233 |
"""Provide a redirect on any GET request.""" |
| 234 |
|
| 235 |
permanent = False |
| 236 |
url = None |
| 237 |
pattern_name = None |
| 238 |
query_string = False |
| 239 |
|
| 240 |
def get_redirect_url(self, *args, **kwargs): |
| 241 |
""" |
| 242 |
Return the URL redirect to. Keyword arguments from the URL pattern |
| 243 |
match generating the redirect request are provided as kwargs to this |
| 244 |
method. |
| 245 |
""" |
| 246 |
if self.url: |
| 247 |
url = self.url % kwargs |
| 248 |
elif self.pattern_name: |
| 249 |
url = reverse(self.pattern_name, args=args, kwargs=kwargs) |
| 250 |
else: |
| 251 |
return None |
| 252 |
|
| 253 |
args = self.request.META.get("QUERY_STRING", "") |
| 254 |
if args and self.query_string: |
| 255 |
url = "%s?%s" % (url, args) |
| 256 |
return url |
| 257 |
|
| 258 |
def get(self, request, *args, **kwargs): |
| 259 |
url = self.get_redirect_url(*args, **kwargs) |
| 260 |
if url: |
| 261 |
if self.permanent: |
| 262 |
return HttpResponsePermanentRedirect(url) |
| 263 |
else: |
| 264 |
return HttpResponseRedirect(url) |
| 265 |
else: |
| 266 |
response = HttpResponseGone() |
| 267 |
log_response("Gone: %s", request.path, response=response, request=request) |
| 268 |
return response |
| 269 |
|
| 270 |
def head(self, request, *args, **kwargs): |
| 271 |
return self.get(request, *args, **kwargs) |
| 272 |
|
| 273 |
def post(self, request, *args, **kwargs): |
| 274 |
return self.get(request, *args, **kwargs) |
| 275 |
|
| 276 |
def options(self, request, *args, **kwargs): |
| 277 |
return self.get(request, *args, **kwargs) |
| 278 |
|
| 279 |
def delete(self, request, *args, **kwargs): |
| 280 |
return self.get(request, *args, **kwargs) |
| 281 |
|
| 282 |
def put(self, request, *args, **kwargs): |
| 283 |
return self.get(request, *args, **kwargs) |
| 284 |
|
| 285 |
def patch(self, request, *args, **kwargs): |
| 286 |
return self.get(request, *args, **kwargs) |