Debian Codegraph @

src/drf_yasg/inspectors/base.py

raw symbols SCIP
1 import inspect
2 import logging
3
4 from rest_framework import serializers
5
6 from .. import openapi
7 from ..utils import force_real_str, get_field_default, get_object_classes, is_list_view
8
9 #: Sentinel value that inspectors must return to signal that they do not know how to
10 # handle an object
11 NotHandled = object()
12
13 logger = logging.getLogger(__name__)
14
15
16 def is_callable_method(cls_or_instance, method_name):
17 method = getattr(cls_or_instance, method_name)
18 if inspect.ismethod(method) and getattr(method, "__self__", None):
19 # bound classmethod or instance method
20 return method, True
21
22 from inspect import getattr_static
23
24 return method, isinstance(
25 getattr_static(cls_or_instance, method_name, None), staticmethod
26 )
27
28
29 def call_view_method(view, method_name, fallback_attr=None, default=None):
30 """Call a view method which might throw an exception. If an exception is thrown, log
31 an informative error message and return the value of fallback_attr, or default if
32 not present. The method must be callable without any arguments except cls or self.
33
34 :param view: view class or instance; if a class is passed, instance methods won't be
35 called
36 :type view: rest_framework.views.APIView or type[rest_framework.views.APIView]
37 :param str method_name: name of a method on the view
38 :param str fallback_attr: name of an attribute on the view to fall back on, if
39 calling the method fails
40 :param default: default value if all else fails
41 :return: view method's return value, or value of view's fallback_attr, or default
42 :rtype: any or None
43 """
44 if hasattr(view, method_name):
45 try:
46 view_method, is_callabale = is_callable_method(view, method_name)
47 if is_callabale:
48 return view_method()
49 except Exception: # pragma: no cover
50 logger.warning(
51 "view's %s.%s raised exception during schema generation; use "
52 "`getattr(self, 'swagger_fake_view', False)` to detect and "
53 "short-circuit this",
54 type(view).__name__,
55 method_name,
56 exc_info=True,
57 )
58
59 if fallback_attr and hasattr(view, fallback_attr):
60 return getattr(view, fallback_attr)
61
62 return default
63
64
65 class BaseInspector:
66 def __init__(self, view, path, method, components, request):
67 """
68 :param rest_framework.views.APIView view: the view associated with this endpoint
69 :param str path: the path component of the operation URL
70 :param str method: the http method of the operation
71 :param openapi.ReferenceResolver components: referenceable components
72 :param rest_framework.request.Request request: the request made against the
73 schema view; can be None
74 """
75 self.view = view
76 self.path = path
77 self.method = method
78 self.components = components
79 self.request = request
80
81 def process_result(self, result, method_name, obj, **kwargs):
82 """After an inspector handles an object (i.e. returns a value other than
83 :data:`.NotHandled`), all inspectors that were probed get the chance to alter
84 the result, in reverse order. The inspector that handled the object is the first
85 to receive a ``process_result`` call with the object it just returned.
86
87 This behavior is similar to the Django request/response middleware processing.
88
89 If this inspector has no post-processing to do, it should just ``return result``
90 (the default implementation).
91
92 :param result: the return value of the winning inspector, or ``None`` if no
93 inspector handled the object
94 :param str method_name: name of the method that was called on the inspector
95 :param obj: first argument passed to inspector method
96 :param kwargs: additional arguments passed to inspector method
97 :return:
98 """
99 return result
100
101 def probe_inspectors(self, inspectors, method_name, obj, initkwargs=None, **kwargs):
102 """Probe a list of inspectors with a given object. The first inspector in the
103 list to return a value that is not :data:`.NotHandled` wins.
104
105 :param list[type[BaseInspector]] inspectors: list of inspectors to probe
106 :param str method_name: name of the target method on the inspector
107 :param obj: first argument to inspector method
108 :param dict initkwargs: extra kwargs for instantiating inspector class
109 :param kwargs: additional arguments to inspector method
110 :return: the return value of the winning inspector, or ``None`` if no inspector
111 handled the object
112 """
113 initkwargs = initkwargs or {}
114 tried_inspectors = []
115
116 for inspector in inspectors:
117 assert inspect.isclass(inspector), (
118 "inspector must be a class, not an object"
119 )
120 assert issubclass(inspector, BaseInspector), (
121 "inspectors must subclass BaseInspector"
122 )
123
124 inspector = inspector(
125 self.view,
126 self.path,
127 self.method,
128 self.components,
129 self.request,
130 **initkwargs,
131 )
132 tried_inspectors.append(inspector)
133 method = getattr(inspector, method_name, None)
134 if method is None:
135 continue
136
137 result = method(obj, **kwargs)
138 if result is not NotHandled:
139 break
140 else: # pragma: no cover
141 logger.warning(
142 "%s ignored because no inspector in %s handled it (operation: %s)",
143 obj,
144 inspectors,
145 method_name,
146 )
147 result = None
148
149 for inspector in reversed(tried_inspectors):
150 result = inspector.process_result(result, method_name, obj, **kwargs)
151
152 return result
153
154 def get_renderer_classes(self):
155 """Get the renderer classes of this view by calling `get_renderers`.
156
157 :return: renderer classes
158 :rtype: list[type[rest_framework.renderers.BaseRenderer]]
159 """
160 return get_object_classes(
161 call_view_method(self.view, "get_renderers", "renderer_classes", [])
162 )
163
164 def get_parser_classes(self):
165 """Get the parser classes of this view by calling `get_parsers`.
166
167 :return: parser classes
168 :rtype: list[type[rest_framework.parsers.BaseParser]]
169 """
170 return get_object_classes(
171 call_view_method(self.view, "get_parsers", "parser_classes", [])
172 )
173
174
175 class PaginatorInspector(BaseInspector):
176 """Base inspector for paginators.
177
178 Responsible for determining extra query parameters and response structure added by
179 given paginators.
180 """
181
182 def get_paginator_parameters(self, paginator):
183 """Get the pagination parameters for a single paginator **instance**.
184
185 Should return :data:`.NotHandled` if this inspector does not know how to handle
186 the given `paginator`.
187
188 :param BasePagination paginator: the paginator
189 :rtype: list[openapi.Parameter]
190 """
191 return NotHandled
192
193 def get_paginated_response(self, paginator, response_schema):
194 """Add appropriate paging fields to a response :class:`.Schema`.
195
196 Should return :data:`.NotHandled` if this inspector does not know how to handle
197 the given `paginator`.
198
199 :param BasePagination paginator: the paginator
200 :param openapi.Schema response_schema: the response schema that must be paged.
201 :rtype: openapi.Schema
202 """
203 return NotHandled
204
205
206 class FilterInspector(BaseInspector):
207 """Base inspector for filter backends.
208
209 Responsible for determining extra query parameters added by given filter backends.
210 """
211
212 def get_filter_parameters(self, filter_backend):
213 """Get the filter parameters for a single filter backend **instance**.
214
215 Should return :data:`.NotHandled` if this inspector does not know how to handle
216 the given `filter_backend`.
217
218 :param BaseFilterBackend filter_backend: the filter backend
219 :rtype: list[openapi.Parameter]
220 """
221 return NotHandled
222
223
224 class FieldInspector(BaseInspector):
225 """Base inspector for serializers and serializer fields."""
226
227 def __init__(self, view, path, method, components, request, field_inspectors):
228 super(FieldInspector, self).__init__(view, path, method, components, request)
229 self.field_inspectors = field_inspectors
230
231 def add_manual_fields(self, serializer_or_field, schema):
232 """Set fields from the ``swagger_schema_fields`` attribute on the Meta class.
233 This method is called only for serializers or fields that are converted into
234 ``openapi.Schema`` objects.
235
236 :param serializer_or_field: serializer or field instance
237 :param openapi.Schema schema: the schema object to be modified in-place
238 """
239 meta = getattr(serializer_or_field, "Meta", None)
240 swagger_schema_fields = getattr(meta, "swagger_schema_fields", {})
241 if swagger_schema_fields:
242 for attr, val in swagger_schema_fields.items():
243 setattr(schema, attr, val)
244
245 def field_to_swagger_object(
246 self, field, swagger_object_type, use_references, **kwargs
247 ):
248 """Convert a drf Serializer or Field instance into a Swagger object.
249
250 Should return :data:`.NotHandled` if this inspector does not know how to handle
251 the given `field`.
252
253 :param rest_framework.serializers.Field field: the source field
254 :param type[openapi.SwaggerDict] swagger_object_type: should be one of Schema,
255 Parameter, Items
256 :param bool use_references: if False, forces all objects to be declared inline
257 instead of by referencing other components
258 :param kwargs: extra attributes for constructing the object;
259 if swagger_object_type is Parameter, ``name`` and ``in_`` should be provided
260 :return: the swagger object
261 :rtype: openapi.Parameter or openapi.Items or openapi.Schema or
262 openapi.SchemaRef
263 """
264 return NotHandled
265
266 def probe_field_inspectors(
267 self, field, swagger_object_type, use_references, **kwargs
268 ):
269 """Helper method for recursively probing `field_inspectors` to handle a given
270 field.
271
272 All arguments are the same as :meth:`.field_to_swagger_object`.
273
274 :rtype: openapi.Parameter or openapi.Items or openapi.Schema or
275 openapi.SchemaRef
276 """
277 return self.probe_inspectors(
278 self.field_inspectors,
279 "field_to_swagger_object",
280 field,
281 {"field_inspectors": self.field_inspectors},
282 swagger_object_type=swagger_object_type,
283 use_references=use_references,
284 **kwargs,
285 )
286
287 def _get_partial_types(self, field, swagger_object_type, use_references, **kwargs):
288 """Helper method to extract generic information from a field and return a
289 partial constructor for the appropriate openapi object.
290
291 All arguments are the same as :meth:`.field_to_swagger_object`.
292
293 The return value is a tuple consisting of:
294
295 * a function for constructing objects of `swagger_object_type`; its prototype
296 is: ::
297
298 def SwaggerType(existing_object=None, **instance_kwargs):
299
300 This function creates an instance of `swagger_object_type`, passing the
301 following attributes to its init, in order of precedence:
302
303 - arguments specified by the ``kwargs`` parameter of
304 :meth:`._get_partial_types`
305 - ``instance_kwargs`` passed to the constructor function
306 - ``title``, ``description``, ``required``, ``x-nullable`` and ``default``
307 inferred from the field, where appropriate
308
309 If ``existing_object`` is not ``None``, it is updated instead of creating a
310 new object.
311
312 * a type that should be used for child objects if `field` is of an array type.
313 This can currently have two values:
314
315 - :class:`.Schema` if `swagger_object_type` is :class:`.Schema`
316 - :class:`.Items` if `swagger_object_type` is :class:`.Parameter` or
317 :class:`.Items`
318
319 :rtype: (function,type[openapi.Schema] or type[openapi.Items])
320 """
321 assert swagger_object_type in (openapi.Schema, openapi.Parameter, openapi.Items)
322 assert not isinstance(field, openapi.SwaggerDict), (
323 "passed field is already a SwaggerDict object"
324 )
325 title = force_real_str(field.label) if field.label else None
326 title = (
327 title if swagger_object_type == openapi.Schema else None
328 ) # only Schema has title
329 help_text = getattr(field, "help_text", None)
330 description = force_real_str(help_text) if help_text else None
331 description = (
332 description if swagger_object_type != openapi.Items else None
333 ) # Items has no description either
334
335 def SwaggerType(existing_object=None, use_field_title=True, **instance_kwargs):
336 if (
337 "required" not in instance_kwargs
338 and swagger_object_type == openapi.Parameter
339 ):
340 instance_kwargs["required"] = field.required
341
342 if (
343 "default" not in instance_kwargs
344 and swagger_object_type != openapi.Items
345 ):
346 default = get_field_default(field)
347 if default not in (None, serializers.empty):
348 instance_kwargs["default"] = default
349
350 if (
351 use_field_title
352 and instance_kwargs.get("type", None) != openapi.TYPE_ARRAY
353 ):
354 instance_kwargs.setdefault("title", title)
355 if description is not None:
356 instance_kwargs.setdefault("description", description)
357
358 if getattr(field, "allow_null", None):
359 instance_kwargs["x_nullable"] = True
360
361 instance_kwargs.update(kwargs)
362
363 if existing_object is not None:
364 assert isinstance(existing_object, swagger_object_type)
365 for key, val in sorted(instance_kwargs.items()):
366 setattr(existing_object, key, val)
367 result = existing_object
368 else:
369 result = swagger_object_type(**instance_kwargs)
370
371 # Provide an option to add manual parameters to a schema
372 # for example, to add examples
373 if swagger_object_type == openapi.Schema:
374 self.add_manual_fields(field, result)
375 return result
376
377 # arrays in Schema have Schema elements, arrays in Parameter and Items have
378 # Items elements
379 child_swagger_type = (
380 openapi.Schema if swagger_object_type == openapi.Schema else openapi.Items
381 )
382 return SwaggerType, child_swagger_type
383
384
385 class SerializerInspector(FieldInspector):
386 def get_schema(self, serializer):
387 """Convert a DRF Serializer instance to an :class:`.openapi.Schema`.
388
389 Should return :data:`.NotHandled` if this inspector does not know how to handle
390 the given `serializer`.
391
392 :param serializers.BaseSerializer serializer: the ``Serializer`` instance
393 :rtype: openapi.Schema
394 """
395 return NotHandled
396
397 def get_request_parameters(self, serializer, in_):
398 """Convert a DRF serializer into a list of :class:`.Parameter`\\ s.
399
400 Should return :data:`.NotHandled` if this inspector does not know how to handle
401 the given `serializer`.
402
403 :param serializers.BaseSerializer serializer: the ``Serializer`` instance
404 :param str in_: the location of the parameters, one of the `openapi.IN_*`
405 constants
406 :rtype: list[openapi.Parameter]
407 """
408 return NotHandled
409
410
411 class ViewInspector(BaseInspector):
412 body_methods = (
413 "PUT",
414 "PATCH",
415 "POST",
416 "DELETE",
417 ) #: methods that are allowed to have a request body
418
419 #: methods that are assumed to require a request body determined by the view's
420 # ``serializer_class``
421 implicit_body_methods = ("PUT", "PATCH", "POST")
422
423 #: methods which are assumed to return a list of objects when present on non-detail
424 # endpoints
425 implicit_list_response_methods = ("GET",)
426
427 # real values set in __init__ to prevent import errors
428 field_inspectors = [] #:
429 filter_inspectors = [] #:
430 paginator_inspectors = [] #:
431
432 def __init__(self, view, path, method, components, request, overrides):
433 """
434 Inspector class responsible for providing :class:`.Operation` definitions given
435 a view, path and method.
436
437 :param dict overrides: manual overrides as passed to
438 :func:`@swagger_auto_schema <.swagger_auto_schema>`
439 """
440 super(ViewInspector, self).__init__(view, path, method, components, request)
441 self.overrides = overrides
442 self._prepend_inspector_overrides("field_inspectors")
443 self._prepend_inspector_overrides("filter_inspectors")
444 self._prepend_inspector_overrides("paginator_inspectors")
445
446 def _prepend_inspector_overrides(self, inspectors):
447 extra_inspectors = self.overrides.get(inspectors, None)
448 if extra_inspectors:
449 default_inspectors = [
450 insp
451 for insp in getattr(self, inspectors)
452 if insp not in extra_inspectors
453 ]
454 setattr(self, inspectors, extra_inspectors + default_inspectors)
455
456 def get_operation(self, operation_keys):
457 """Get an :class:`.Operation` for the given API endpoint (path, method).
458 This includes query, body parameters and response schemas.
459
460 :param tuple[str] operation_keys: an array of keys describing the hierarchical
461 layout of this view in the API; e.g. ``('snippets', 'list')``,
462 ``('snippets', 'retrieve')``, etc.
463 :rtype: openapi.Operation
464 """
465 raise NotImplementedError("ViewInspector must implement get_operation()!")
466
467 def is_list_view(self):
468 """Determine whether this view is a list or a detail view. The difference
469 between the two is that detail views depend on a pk/id path parameter. Note that
470 a non-detail view does not necessarily imply a list response
471 (:meth:`.has_list_response`), nor are list responses limited to non-detail
472 views.
473
474 For example, one might have a `/topic/<pk>/posts` endpoint which is a detail
475 view that has a list response.
476
477 :rtype: bool"""
478 return is_list_view(self.path, self.method, self.view)
479
480 def has_list_response(self):
481 """Determine whether this view returns multiple objects. By default this is any
482 non-detail view (see :meth:`.is_list_view`) whose request method is one of
483 :attr:`.implicit_list_response_methods`.
484
485 :rtype: bool
486 """
487 return self.is_list_view() and (
488 self.method.upper() in self.implicit_list_response_methods
489 )
490
491 def should_filter(self):
492 """Determine whether filter backend parameters should be included for this
493 request.
494
495 :rtype: bool
496 """
497 return getattr(self.view, "filter_backends", None) and self.has_list_response()
498
499 def get_filter_parameters(self):
500 """Return the parameters added to the view by its filter backends.
501
502 :rtype: list[openapi.Parameter]
503 """
504 if not self.should_filter():
505 return []
506
507 fields = []
508 for filter_backend in getattr(self.view, "filter_backends"):
509 fields += (
510 self.probe_inspectors(
511 self.filter_inspectors, "get_filter_parameters", filter_backend()
512 )
513 or []
514 )
515
516 return fields
517
518 def should_page(self):
519 """Determine whether paging parameters and structure should be added to this
520 operation's request and response.
521
522 :rtype: bool
523 """
524 return getattr(self.view, "paginator", None) and self.has_list_response()
525
526 def get_pagination_parameters(self):
527 """Return the parameters added to the view by its paginator.
528
529 :rtype: list[openapi.Parameter]
530 """
531 if not self.should_page():
532 return []
533
534 return (
535 self.probe_inspectors(
536 self.paginator_inspectors,
537 "get_paginator_parameters",
538 getattr(self.view, "paginator"),
539 )
540 or []
541 )
542
543 def serializer_to_schema(self, serializer):
544 """Convert a serializer to an OpenAPI :class:`.Schema`.
545
546 :param serializers.BaseSerializer serializer: the ``Serializer`` instance
547 :returns: the converted :class:`.Schema`, or ``None`` in case of an unknown
548 serializer
549 :rtype: openapi.Schema or openapi.SchemaRef
550 """
551 return self.probe_inspectors(
552 self.field_inspectors,
553 "get_schema",
554 serializer,
555 {"field_inspectors": self.field_inspectors},
556 )
557
558 def serializer_to_parameters(self, serializer, in_):
559 """Convert a serializer to a possibly empty list of :class:`.Parameter`\\ s.
560
561 :param serializers.BaseSerializer serializer: the ``Serializer`` instance
562 :param str in_: the location of the parameters, one of the `openapi.IN_*`
563 constants
564 :rtype: list[openapi.Parameter]
565 """
566 return (
567 self.probe_inspectors(
568 self.field_inspectors,
569 "get_request_parameters",
570 serializer,
571 {"field_inspectors": self.field_inspectors},
572 in_=in_,
573 )
574 or []
575 )
576
577 def get_paginated_response(self, response_schema):
578 """Add appropriate paging fields to a response :class:`.Schema`.
579
580 :param openapi.Schema response_schema: the response schema that must be paged.
581 :returns: the paginated response class:`.Schema`, or ``None`` in case of an
582 unknown pagination scheme
583 :rtype: openapi.Schema
584 """
585 return self.probe_inspectors(
586 self.paginator_inspectors,
587 "get_paginated_response",
588 getattr(self.view, "paginator"),
589 response_schema=response_schema,
590 )