Debian Codegraph @

rest_framework/views.py

raw
1 """
2 Provides an APIView class that is the base of all views in REST framework.
3 """
4 from django.conf import settings
5 from django.core.exceptions import PermissionDenied
6 from django.db import connections, models
7 from django.http import Http404
8 from django.http.response import HttpResponseBase
9 from django.utils.cache import patch_vary_headers
10 from django.utils.encoding import smart_str
11 from django.views.decorators.csrf import csrf_exempt
12 from django.views.generic import View
13
14 from rest_framework import exceptions, status
15 from rest_framework.compat import split_header_value
16 from rest_framework.request import Request
17 from rest_framework.response import Response
18 from rest_framework.schemas import DefaultSchema
19 from rest_framework.settings import api_settings
20 from rest_framework.utils import formatting
21
22
23 def get_view_name(view):
24 """
25 Given a view instance, return a textual name to represent the view.
26 This name is used in the browsable API, and in OPTIONS responses.
27
28 This function is the default for the `VIEW_NAME_FUNCTION` setting.
29 """
30 # Name may be set by some Views, such as a ViewSet.
31 name = getattr(view, 'name', None)
32 if name is not None:
33 return name
34
35 name = view.__class__.__name__
36 name = formatting.remove_trailing_string(name, 'View')
37 name = formatting.remove_trailing_string(name, 'ViewSet')
38 name = formatting.camelcase_to_spaces(name)
39
40 # Suffix may be set by some Views, such as a ViewSet.
41 suffix = getattr(view, 'suffix', None)
42 if suffix:
43 name += ' ' + suffix
44
45 return name
46
47
48 def get_view_description(view, html=False):
49 """
50 Given a view instance, return a textual description to represent the view.
51 This name is used in the browsable API, and in OPTIONS responses.
52
53 This function is the default for the `VIEW_DESCRIPTION_FUNCTION` setting.
54 """
55 # Description may be set by some Views, such as a ViewSet.
56 description = getattr(view, 'description', None)
57 if description is None:
58 description = view.__class__.__doc__ or ''
59
60 description = formatting.dedent(smart_str(description))
61 if html:
62 return formatting.markup_description(description)
63 return description
64
65
66 def set_rollback():
67 for db in connections.all(initialized_only=True):
68 if db.settings_dict['ATOMIC_REQUESTS'] and db.in_atomic_block:
69 db.set_rollback(True)
70
71
72 def exception_handler(exc, context):
73 """
74 Returns the response that should be used for any given exception.
75
76 By default we handle the REST framework `APIException`, and also
77 Django's built-in `Http404` and `PermissionDenied` exceptions.
78
79 Any unhandled exceptions may return `None`, which will cause a 500 error
80 to be raised.
81 """
82 if isinstance(exc, Http404):
83 exc = exceptions.NotFound(*(exc.args))
84 elif isinstance(exc, PermissionDenied):
85 exc = exceptions.PermissionDenied(*(exc.args))
86
87 if isinstance(exc, exceptions.APIException):
88 headers = {}
89 if getattr(exc, 'auth_header', None):
90 headers['WWW-Authenticate'] = exc.auth_header
91 if getattr(exc, 'wait', None):
92 headers['Retry-After'] = '%d' % exc.wait
93
94 if isinstance(exc.detail, (list, dict)):
95 data = exc.detail
96 else:
97 data = {'detail': exc.detail}
98
99 set_rollback()
100 return Response(data, status=exc.status_code, headers=headers)
101
102 return None
103
104
105 class APIView(View):
106
107 # The following policies may be set at either globally, or per-view.
108 renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES
109 parser_classes = api_settings.DEFAULT_PARSER_CLASSES
110 authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES
111 throttle_classes = api_settings.DEFAULT_THROTTLE_CLASSES
112 permission_classes = api_settings.DEFAULT_PERMISSION_CLASSES
113 content_negotiation_class = api_settings.DEFAULT_CONTENT_NEGOTIATION_CLASS
114 metadata_class = api_settings.DEFAULT_METADATA_CLASS
115 versioning_class = api_settings.DEFAULT_VERSIONING_CLASS
116
117 # Allow dependency injection of other settings to make testing easier.
118 settings = api_settings
119
120 schema = DefaultSchema()
121
122 @classmethod
123 def as_view(cls, **initkwargs):
124 """
125 Store the original class on the view function.
126
127 This allows us to discover information about the view when we do URL
128 reverse lookups. Used for breadcrumb generation.
129 """
130 if isinstance(getattr(cls, 'queryset', None), models.query.QuerySet):
131 def force_evaluation():
132 raise RuntimeError(
133 'Do not evaluate the `.queryset` attribute directly, '
134 'as the result will be cached and reused between requests. '
135 'Use `.all()` or call `.get_queryset()` instead.'
136 )
137 cls.queryset._fetch_all = force_evaluation
138
139 view = super().as_view(**initkwargs)
140 view.cls = cls
141 view.initkwargs = initkwargs
142
143 # Exempt all DRF views from Django's LoginRequiredMiddleware. Users should set
144 # DEFAULT_PERMISSION_CLASSES to 'rest_framework.permissions.IsAuthenticated' instead
145 view.login_required = False
146
147 # Note: session based authentication is explicitly CSRF validated,
148 # all other authentication is CSRF exempt.
149 return csrf_exempt(view)
150
151 @property
152 def allowed_methods(self):
153 """
154 Wrap Django's private `_allowed_methods` interface in a public property.
155 """
156 return self._allowed_methods()
157
158 @property
159 def default_response_headers(self):
160 headers = {
161 'Allow': ', '.join(self.allowed_methods),
162 }
163 if len(self.renderer_classes) > 1:
164 headers['Vary'] = 'Accept'
165 return headers
166
167 def http_method_not_allowed(self, request, *args, **kwargs):
168 """
169 If `request.method` does not correspond to a handler method,
170 determine what kind of exception to raise.
171 """
172 raise exceptions.MethodNotAllowed(request.method)
173
174 def permission_denied(self, request, message=None, code=None):
175 """
176 If request is not permitted, determine what kind of exception to raise.
177 """
178 if request.authenticators and not request.successful_authenticator:
179 raise exceptions.NotAuthenticated()
180 raise exceptions.PermissionDenied(detail=message, code=code)
181
182 def throttled(self, request, wait):
183 """
184 If request is throttled, determine what kind of exception to raise.
185 """
186 raise exceptions.Throttled(wait)
187
188 def get_authenticate_header(self, request):
189 """
190 If a request is unauthenticated, determine the WWW-Authenticate
191 header to use for 401 responses, if any.
192 """
193 authenticators = self.get_authenticators()
194 if authenticators:
195 return authenticators[0].authenticate_header(request)
196
197 def get_parser_context(self, http_request):
198 """
199 Returns a dict that is passed through to Parser.parse(),
200 as the `parser_context` keyword argument.
201 """
202 # Note: Additionally `request` and `encoding` will also be added
203 # to the context by the Request object.
204 return {
205 'view': self,
206 'args': getattr(self, 'args', ()),
207 'kwargs': getattr(self, 'kwargs', {})
208 }
209
210 def get_renderer_context(self):
211 """
212 Returns a dict that is passed through to Renderer.render(),
213 as the `renderer_context` keyword argument.
214 """
215 # Note: Additionally 'response' will also be added to the context,
216 # by the Response object.
217 return {
218 'view': self,
219 'args': getattr(self, 'args', ()),
220 'kwargs': getattr(self, 'kwargs', {}),
221 'request': getattr(self, 'request', None)
222 }
223
224 def get_exception_handler_context(self):
225 """
226 Returns a dict that is passed through to EXCEPTION_HANDLER,
227 as the `context` argument.
228 """
229 return {
230 'view': self,
231 'args': getattr(self, 'args', ()),
232 'kwargs': getattr(self, 'kwargs', {}),
233 'request': getattr(self, 'request', None)
234 }
235
236 def get_view_name(self):
237 """
238 Return the view name, as used in OPTIONS responses and in the
239 browsable API.
240 """
241 func = self.settings.VIEW_NAME_FUNCTION
242 return func(self)
243
244 def get_view_description(self, html=False):
245 """
246 Return some descriptive text for the view, as used in OPTIONS responses
247 and in the browsable API.
248 """
249 func = self.settings.VIEW_DESCRIPTION_FUNCTION
250 return func(self, html)
251
252 # API policy instantiation methods
253
254 def get_format_suffix(self, **kwargs):
255 """
256 Determine if the request includes a '.json' style format suffix
257 """
258 if self.settings.FORMAT_SUFFIX_KWARG:
259 return kwargs.get(self.settings.FORMAT_SUFFIX_KWARG)
260
261 def get_renderers(self):
262 """
263 Instantiates and returns the list of renderers that this view can use.
264 """
265 return [renderer() for renderer in self.renderer_classes]
266
267 def get_parsers(self):
268 """
269 Instantiates and returns the list of parsers that this view can use.
270 """
271 return [parser() for parser in self.parser_classes]
272
273 def get_authenticators(self):
274 """
275 Instantiates and returns the list of authenticators that this view can use.
276 """
277 return [auth() for auth in self.authentication_classes]
278
279 def get_permissions(self):
280 """
281 Instantiates and returns the list of permissions that this view requires.
282 """
283 return [permission() for permission in self.permission_classes]
284
285 def get_throttles(self):
286 """
287 Instantiates and returns the list of throttles that this view uses.
288 """
289 return [throttle() for throttle in self.throttle_classes]
290
291 def get_content_negotiator(self):
292 """
293 Instantiate and return the content negotiation class to use.
294 """
295 if not getattr(self, '_negotiator', None):
296 self._negotiator = self.content_negotiation_class()
297 return self._negotiator
298
299 def get_exception_handler(self):
300 """
301 Returns the exception handler that this view uses.
302 """
303 return self.settings.EXCEPTION_HANDLER
304
305 # API policy implementation methods
306
307 def perform_content_negotiation(self, request, force=False):
308 """
309 Determine which renderer and media type to use render the response.
310 """
311 renderers = self.get_renderers()
312 conneg = self.get_content_negotiator()
313
314 try:
315 return conneg.select_renderer(request, renderers, self.format_kwarg)
316 except Exception:
317 if force:
318 return (renderers[0], renderers[0].media_type)
319 raise
320
321 def perform_authentication(self, request):
322 """
323 Perform authentication on the incoming request.
324
325 Note that if you override this and simply 'pass', then authentication
326 will instead be performed lazily, the first time either
327 `request.user` or `request.auth` is accessed.
328 """
329 request.user
330
331 def check_permissions(self, request):
332 """
333 Check if the request should be permitted.
334 Raises an appropriate exception if the request is not permitted.
335 """
336 for permission in self.get_permissions():
337 if not permission.has_permission(request, self):
338 self.permission_denied(
339 request,
340 message=getattr(permission, 'message', None),
341 code=getattr(permission, 'code', None)
342 )
343
344 def check_object_permissions(self, request, obj):
345 """
346 Check if the request should be permitted for a given object.
347 Raises an appropriate exception if the request is not permitted.
348 """
349 for permission in self.get_permissions():
350 if not permission.has_object_permission(request, self, obj):
351 self.permission_denied(
352 request,
353 message=getattr(permission, 'message', None),
354 code=getattr(permission, 'code', None)
355 )
356
357 def check_throttles(self, request):
358 """
359 Check if request should be throttled.
360 Raises an appropriate exception if the request is throttled.
361 """
362 throttle_durations = []
363 for throttle in self.get_throttles():
364 if not throttle.allow_request(request, self):
365 throttle_durations.append(throttle.wait())
366
367 if throttle_durations:
368 # Filter out `None` values which may happen in case of config / rate
369 # changes, see #1438
370 durations = [
371 duration for duration in throttle_durations
372 if duration is not None
373 ]
374
375 duration = max(durations, default=None)
376 self.throttled(request, duration)
377
378 def determine_version(self, request, *args, **kwargs):
379 """
380 If versioning is being used, then determine any API version for the
381 incoming request. Returns a two-tuple of (version, versioning_scheme)
382 """
383 if self.versioning_class is None:
384 return (None, None)
385 scheme = self.versioning_class()
386 return (scheme.determine_version(request, *args, **kwargs), scheme)
387
388 # Dispatch methods
389
390 def initialize_request(self, request, *args, **kwargs):
391 """
392 Returns the initial request object.
393 """
394 parser_context = self.get_parser_context(request)
395
396 return Request(
397 request,
398 parsers=self.get_parsers(),
399 authenticators=self.get_authenticators(),
400 negotiator=self.get_content_negotiator(),
401 parser_context=parser_context
402 )
403
404 def initial(self, request, *args, **kwargs):
405 """
406 Runs anything that needs to occur prior to calling the method handler.
407 """
408 self.format_kwarg = self.get_format_suffix(**kwargs)
409
410 # Perform content negotiation and store the accepted info on the request
411 neg = self.perform_content_negotiation(request)
412 request.accepted_renderer, request.accepted_media_type = neg
413
414 # Determine the API version, if versioning is in use.
415 version, scheme = self.determine_version(request, *args, **kwargs)
416 request.version, request.versioning_scheme = version, scheme
417
418 # Ensure that the incoming request is permitted
419 self.perform_authentication(request)
420 self.check_permissions(request)
421 self.check_throttles(request)
422
423 def finalize_response(self, request, response, *args, **kwargs):
424 """
425 Returns the final response object.
426 """
427 # Make the error obvious if a proper response is not returned
428 assert isinstance(response, HttpResponseBase), (
429 'Expected a `Response`, `HttpResponse` or `StreamingHttpResponse` '
430 'to be returned from the view, but received a `%s`'
431 % type(response)
432 )
433
434 if isinstance(response, Response):
435 if not getattr(request, 'accepted_renderer', None):
436 neg = self.perform_content_negotiation(request, force=True)
437 request.accepted_renderer, request.accepted_media_type = neg
438
439 response.accepted_renderer = request.accepted_renderer
440 response.accepted_media_type = request.accepted_media_type
441 response.renderer_context = self.get_renderer_context()
442
443 # Add new vary headers to the response instead of overwriting.
444 vary_headers = self.headers.pop('Vary', None)
445 if vary_headers is not None:
446 patch_vary_headers(response, list(split_header_value(vary_headers)))
447
448 for key, value in self.headers.items():
449 response[key] = value
450
451 return response
452
453 def handle_exception(self, exc):
454 """
455 Handle any exception that occurs, by returning an appropriate response,
456 or re-raising the error.
457 """
458 if isinstance(exc, (exceptions.NotAuthenticated,
459 exceptions.AuthenticationFailed)):
460 # WWW-Authenticate header for 401 responses, else coerce to 403
461 auth_header = self.get_authenticate_header(self.request)
462
463 if auth_header:
464 exc.auth_header = auth_header
465 else:
466 exc.status_code = status.HTTP_403_FORBIDDEN
467
468 exception_handler = self.get_exception_handler()
469
470 context = self.get_exception_handler_context()
471 response = exception_handler(exc, context)
472
473 if response is None:
474 self.raise_uncaught_exception(exc)
475
476 response.exception = True
477 return response
478
479 def raise_uncaught_exception(self, exc):
480 if settings.DEBUG:
481 request = self.request
482 renderer_format = getattr(request.accepted_renderer, 'format')
483 use_plaintext_traceback = renderer_format not in ('html', 'api', 'admin')
484 request.force_plaintext_errors(use_plaintext_traceback)
485 raise exc
486
487 # Note: Views are made CSRF exempt from within `as_view` as to prevent
488 # accidental removal of this exemption in cases where `dispatch` needs to
489 # be overridden.
490 def dispatch(self, request, *args, **kwargs):
491 """
492 Dispatch the incoming request to the appropriate handler method.
493
494 This method implements the core request/response lifecycle for
495 Django REST Framework views:
496
497 1. Wraps the incoming Django HttpRequest in a REST framework Request.
498 2. Performs content negotiation, authentication, permission, and
499 throttling checks.
500 3. Resolves and calls the appropriate HTTP method handler
501 (e.g. get(), post(), put()).
502 4. Handles any exceptions raised during processing and converts
503 them into appropriate Response objects.
504 5. Finalizes and returns the response with proper rendering
505 and headers applied.
506 """
507 self.args = args
508 self.kwargs = kwargs
509 request = self.initialize_request(request, *args, **kwargs)
510 self.request = request
511 self.headers = self.default_response_headers # deprecate?
512
513 try:
514 self.initial(request, *args, **kwargs)
515
516 # Get the appropriate handler method
517 if request.method.lower() in self.http_method_names:
518 handler = getattr(self, request.method.lower(),
519 self.http_method_not_allowed)
520 else:
521 handler = self.http_method_not_allowed
522
523 response = handler(request, *args, **kwargs)
524
525 except Exception as exc:
526 response = self.handle_exception(exc)
527
528 self.response = self.finalize_response(request, response, *args, **kwargs)
529 return self.response
530
531 def options(self, request, *args, **kwargs):
532 """
533 Handler method for HTTP 'OPTIONS' request.
534 """
535 if self.metadata_class is None:
536 return self.http_method_not_allowed(request, *args, **kwargs)
537 data = self.metadata_class().determine_metadata(request, self)
538 return Response(data, status=status.HTTP_200_OK)