Debian Codegraph @

src/drf_yasg/utils.py

raw symbols SCIP
1 import inspect
2 import logging
3 import textwrap
4 from decimal import Decimal
5
6 import pytz
7 from django.db import models
8 from django.utils.encoding import force_str
9 from rest_framework import serializers, status
10 from rest_framework.mixins import (
11 DestroyModelMixin,
12 ListModelMixin,
13 RetrieveModelMixin,
14 UpdateModelMixin,
15 )
16 from rest_framework.parsers import FileUploadParser
17 from rest_framework.request import is_form_media_type
18 from rest_framework.settings import api_settings as rest_framework_settings
19 from rest_framework.utils import encoders, json
20 from rest_framework.views import APIView
21
22 from .app_settings import swagger_settings
23
24 try:
25 import zoneinfo
26 except ImportError:
27 try:
28 from backports import zoneinfo
29 except ImportError:
30 zoneinfo = None
31
32
33 logger = logging.getLogger(__name__)
34
35
36 class no_body(object):
37 """Used as a sentinel value to forcibly remove the body of a request via
38 :func:`.swagger_auto_schema`."""
39
40 pass
41
42
43 class unset(object):
44 """Used as a sentinel value for function parameters not set by the caller where
45 ``None`` would be a valid value."""
46
47 pass
48
49
50 def swagger_auto_schema(
51 method=None,
52 methods=None,
53 auto_schema=unset,
54 request_body=None,
55 query_serializer=None,
56 manual_parameters=None,
57 operation_id=None,
58 operation_description=None,
59 operation_summary=None,
60 security=None,
61 deprecated=None,
62 responses=None,
63 field_inspectors=None,
64 filter_inspectors=None,
65 paginator_inspectors=None,
66 tags=None,
67 produces=None,
68 consumes=None,
69 **extra_overrides,
70 ):
71 """Decorate a view method to customize the :class:`.Operation` object generated from
72 it.
73
74 `method` and `methods` are mutually exclusive and must only be present when
75 decorating a view method that accepts more than one HTTP request method.
76
77 The `auto_schema` and `operation_description` arguments take precedence over view-
78 or method-level values.
79
80 :param str method: for multi-method views, the http method the options should apply
81 to
82 :param list[str] methods: for multi-method views, the http methods the options
83 should apply to
84 :param drf_yasg.inspectors.SwaggerAutoSchema auto_schema: custom class to use for
85 generating the Operation object;
86 this overrides both the class-level ``swagger_schema`` attribute and the
87 ``DEFAULT_AUTO_SCHEMA_CLASS`` setting, and can be set to ``None`` to prevent
88 this operation from being generated
89 :param request_body: custom request body which will be used as the ``schema``
90 property of a :class:`.Parameter` with ``in: 'body'``.
91
92 A Schema or SchemaRef is not valid if this request consumes form-data, because
93 ``form`` and ``body`` parameters are mutually exclusive in an
94 :class:`.Operation`. If you need to set custom ``form`` parameters, you can use
95 the `manual_parameters` argument.
96
97 If a ``Serializer`` class or instance is given, it will be automatically
98 converted into a :class:`.Schema` used as a ``body`` :class:`.Parameter`, or
99 into a list of ``form`` :class:`.Parameter`\\ s, as appropriate.
100 :type request_body: drf_yasg.openapi.Schema or drf_yasg.openapi.SchemaRef or
101 rest_framework.serializers.Serializer or type[no_body]
102
103 :param rest_framework.serializers.Serializer query_serializer: if you use a
104 ``Serializer`` to parse query parameters, you can pass it here and have
105 :class:`.Parameter` objects be generated automatically from it.
106
107 If any ``Field`` on the serializer cannot be represented as a ``query``
108 :class:`.Parameter` (e.g. nested Serializers, file fields, ...), the schema
109 generation will fail with an error.
110
111 Schema generation will also fail if the name of any Field on the
112 `query_serializer` conflicts with parameters generated by ``filter_backends`` or
113 ``paginator``.
114
115 :param list[drf_yasg.openapi.Parameter] manual_parameters: a list of manual
116 parameters to override the automatically generated ones
117
118 :class:`.Parameter`\\ s are identified by their (``name``, ``in``) combination,
119 and any parameters given here will fully override automatically generated
120 parameters if they collide.
121
122 It is an error to supply ``form`` parameters when the request does not consume
123 form-data.
124
125 :param str operation_id: operation ID override; the operation ID must be unique
126 across the whole API
127 :param str operation_description: operation description override
128 :param str operation_summary: operation summary string
129 :param list[dict] security: security requirements override; used to specify which
130 authentication mechanism is required to call this API; an empty list marks the
131 endpoint as unauthenticated (i.e. removes all accepted authentication schemes),
132 and ``None`` will inherit the top-level security requirements
133 :param bool deprecated: deprecation status for operation
134 :param responses: a dict of documented manual responses keyed on response status
135 code. If no success (``2xx``) response is given, one will automatically be
136 generated from the request body and http method. If any ``2xx`` response is
137 given the automatic response is suppressed.
138
139 * if a plain string is given as value, a :class:`.Response` with no body and
140 that string as its description will be generated
141 * if ``None`` is given as a value, the response is ignored; this is mainly
142 useful for disabling default 2xx responses, i.e.
143 ``responses={200: None, 302: 'something'}``
144 * if a :class:`.Schema`, :class:`.SchemaRef` is given, a :class:`.Response`
145 with the schema as its body and an empty description will be generated
146 * a ``Serializer`` class or instance will be converted into a :class:`.Schema`
147 and treated as above
148 * a :class:`.Response` object will be used as-is; however if its ``schema``
149 attribute is a ``Serializer``, it will automatically be converted into a
150 :class:`.Schema`
151 :type responses: dict[int or str, (drf_yasg.openapi.Schema or
152 drf_yasg.openapi.SchemaRef or drf_yasg.openapi.Response or str or
153 rest_framework.serializers.Serializer)]
154
155 :param list[type[drf_yasg.inspectors.FieldInspector]] field_inspectors: extra
156 serializer and field inspectors; these will be tried before
157 :attr:`.ViewInspector.field_inspectors` on the
158 :class:`.inspectors.SwaggerAutoSchema`
159 :param list[type[drf_yasg.inspectors.FilterInspector]] filter_inspectors: extra
160 filter inspectors; these will be tried before
161 :attr:`.ViewInspector.filter_inspectors` on the
162 :class:`.inspectors.SwaggerAutoSchema`
163 :param list[type[drf_yasg.inspectors.PaginatorInspector]] paginator_inspectors:
164 extra paginator inspectors; these will be tried before
165 :attr:`.ViewInspector.paginator_inspectors` on the
166 :class:`.inspectors.SwaggerAutoSchema`
167 :param list[str] tags: tags override
168 :param list[str] produces: produces override
169 :param list[str] consumes: consumes override
170 :param extra_overrides: extra values that will be saved into the ``overrides`` dict;
171 these values will be available in the handling
172 :class:`.inspectors.SwaggerAutoSchema` instance via ``self.overrides``
173 """
174
175 def decorator(view_method):
176 assert not any(hm in extra_overrides for hm in APIView.http_method_names), (
177 "HTTP method names not allowed here"
178 )
179 data = {
180 "consumes": consumes,
181 "deprecated": deprecated,
182 "field_inspectors": list(field_inspectors) if field_inspectors else None,
183 "filter_inspectors": list(filter_inspectors) if filter_inspectors else None,
184 "manual_parameters": manual_parameters,
185 "operation_description": operation_description,
186 "operation_id": operation_id,
187 "operation_summary": operation_summary,
188 "paginator_inspectors": list(paginator_inspectors)
189 if paginator_inspectors
190 else None,
191 "produces": produces,
192 "query_serializer": query_serializer,
193 "request_body": request_body,
194 "responses": responses,
195 "security": security,
196 "tags": list(tags) if tags else None,
197 }
198 data = filter_none(data)
199 if auto_schema is not unset:
200 data["auto_schema"] = auto_schema
201 data.update(extra_overrides)
202 if not data: # pragma: no cover
203 # no overrides to set, no use in doing more work
204 return view_method
205
206 # if the method is an @action, it will have a bind_to_methods attribute, or a
207 # mapping attribute for drf>3.8
208 bind_to_methods = getattr(view_method, "bind_to_methods", [])
209 mapping = getattr(view_method, "mapping", {})
210 mapping_methods = [
211 mth for mth, name in mapping.items() if name == view_method.__name__
212 ]
213 action_http_methods = bind_to_methods + mapping_methods
214
215 # if the method is actually a function based view (@api_view), it will have a
216 # 'cls' attribute
217 view_cls = getattr(view_method, "cls", None)
218 api_view_http_methods = [
219 m
220 for m in getattr(view_cls, "http_method_names", [])
221 if hasattr(view_cls, m)
222 ]
223
224 available_http_methods = api_view_http_methods + action_http_methods
225 existing_data = getattr(view_method, "_swagger_auto_schema", {})
226
227 _methods = methods
228 if methods or method:
229 assert available_http_methods, (
230 "`method` or `methods` can only be specified on @action or @api_view "
231 "views"
232 )
233 assert bool(methods) != bool(method), "specify either method or methods"
234 assert not isinstance(methods, str), (
235 "`methods` expects to receive a list of methods;"
236 " use `method` for a single argument"
237 )
238 if method:
239 _methods = [method.lower()]
240 else:
241 _methods = [mth.lower() for mth in methods]
242 assert all(mth in available_http_methods for mth in _methods), (
243 "http method not bound to view"
244 )
245 assert not any(mth in existing_data for mth in _methods), (
246 "http method defined multiple times"
247 )
248
249 if available_http_methods:
250 # action or api_view
251 assert bool(api_view_http_methods) != bool(action_http_methods), (
252 "this should never happen"
253 )
254
255 if len(available_http_methods) > 1:
256 assert _methods, (
257 "on multi-method api_view or action, you must specify "
258 "swagger_auto_schema on a per-method basis using one of the "
259 "`method` or `methods` arguments"
260 )
261 else:
262 # for a single-method view we assume that single method as the decorator
263 # target
264 _methods = _methods or available_http_methods
265
266 assert not any(
267 hasattr(getattr(view_cls, mth, None), "_swagger_auto_schema")
268 for mth in _methods
269 ), "swagger_auto_schema applied twice to method"
270 assert not any(mth in existing_data for mth in _methods), (
271 "swagger_auto_schema applied twice to method"
272 )
273 existing_data.update((mth.lower(), data) for mth in _methods)
274 view_method._swagger_auto_schema = existing_data
275 else:
276 assert not _methods, (
277 "the methods argument should only be specified when decorating an "
278 "action; you should also ensure that you put the swagger_auto_schema "
279 "decorator AFTER (above) the _route decorator"
280 )
281 assert not existing_data, "swagger_auto_schema applied twice to method"
282 view_method._swagger_auto_schema = data
283
284 return view_method
285
286 return decorator
287
288
289 def swagger_serializer_method(serializer_or_field):
290 """
291 Decorates the method of a serializers.SerializerMethodField
292 to hint as to how Swagger should be generated for this field.
293
294 :param serializer_or_field: ``Serializer``/``Field`` class or instance
295 :return:
296 """
297
298 def decorator(serializer_method):
299 # stash the serializer for SerializerMethodFieldInspector to find
300 serializer_method._swagger_serializer = serializer_or_field
301 return serializer_method
302
303 return decorator
304
305
306 def is_list_view(path, method, view):
307 """Check if the given path/method appears to represent a list view (as opposed to a
308 detail/instance view).
309
310 :param str path: view path
311 :param str method: http method
312 :param APIView view: target view
313 :rtype: bool
314 """
315 # for ViewSets, it could be the default 'list' action, or an @action(detail=False)
316 action = getattr(view, "action", "")
317 detail = getattr(view, "detail", None)
318 suffix = getattr(view, "suffix", None)
319 if action in ("list", "create") or detail is False or suffix == "List":
320 return True
321
322 if (
323 action in ("retrieve", "update", "partial_update", "destroy")
324 or method.lower() != "get"
325 # a detail action is surely not a list route
326 or detail is True
327 or suffix == "Instance"
328 ):
329 return False
330
331 if isinstance(view, ListModelMixin):
332 return True
333
334 # for GenericAPIView, if it's a detail view it can't also be a list view
335 if isinstance(view, (RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin)):
336 return False
337
338 # if the last component in the path is parameterized it's probably not a list view
339 path_components = path.strip("/").split("/")
340 if path_components and "{" in path_components[-1]:
341 return False
342
343 # otherwise assume it's a list view
344 return True
345
346
347 def guess_response_status(method):
348 if method == "post":
349 return status.HTTP_201_CREATED
350 elif method == "delete":
351 return status.HTTP_204_NO_CONTENT
352 else:
353 return status.HTTP_200_OK
354
355
356 def param_list_to_dict(parameters):
357 """Transform a list of :class:`.Parameter` objects into an ``dict`` keyed on
358 the ``(name, in_)`` tuple of each parameter.
359
360 Raises an ``AssertionError`` if `parameters` contains duplicate parameters (by their
361 name + in combination).
362
363 :param list[drf_yasg.openapi.Parameter] parameters: the list of parameters
364 :return: `parameters` keyed by ``(name, in_)``
365 :rtype: dict[(str,str),drf_yasg.openapi.Parameter]
366 """
367 result = {(param.name, param.in_): param for param in parameters}
368 assert len(result) == len(parameters), "duplicate Parameters found"
369 return result
370
371
372 def merge_params(parameters, overrides):
373 """Merge `overrides` into `parameters`. This is the same as appending `overrides` to
374 `parameters`, but any element of `parameters` whose ``(name, in_)`` tuple collides
375 with an element in `overrides` is replaced by it.
376
377 Raises an ``AssertionError`` if either list contains duplicate parameters.
378
379 :param list[drf_yasg.openapi.Parameter] parameters: initial parameters
380 :param list[drf_yasg.openapi.Parameter] overrides: overriding parameters
381 :return: merged list
382 :rtype: list[drf_yasg.openapi.Parameter]
383 """
384 return list(
385 (param_list_to_dict(parameters) | param_list_to_dict(overrides)).values()
386 )
387
388
389 def filter_none(obj):
390 """Remove ``None`` values from tuples, lists or dictionaries. Return other objects
391 as-is.
392
393 :param obj: the object
394 :return: collection with ``None`` values removed
395 """
396 if obj is None:
397 return None
398 new_obj = None
399 if isinstance(obj, dict):
400 new_obj = type(obj)(
401 (k, v) for k, v in obj.items() if k is not None and v is not None
402 )
403 if isinstance(obj, (list, tuple)):
404 new_obj = type(obj)(v for v in obj if v is not None)
405 if new_obj is not None and len(new_obj) != len(obj):
406 return new_obj # pragma: no cover
407 return obj
408
409
410 def force_serializer_instance(serializer):
411 """Force `serializer` into a ``Serializer`` instance. If it is not a ``Serializer``
412 class or instance, raises an assertion error.
413
414 :param serializer: serializer class or instance
415 :type serializer: serializers.BaseSerializer or type[serializers.BaseSerializer]
416 :return: serializer instance
417 :rtype: serializers.BaseSerializer
418 """
419 if inspect.isclass(serializer):
420 assert issubclass(serializer, serializers.BaseSerializer), (
421 "Serializer required, not %s" % serializer.__name__
422 )
423 return serializer()
424
425 assert isinstance(serializer, serializers.BaseSerializer), (
426 "Serializer class or instance required, not %s" % type(serializer).__name__
427 )
428 return serializer
429
430
431 def get_serializer_class(serializer):
432 """Given a ``Serializer`` class or instance, return the ``Serializer`` class.
433 If `serializer` is not a ``Serializer`` class or instance, raises an assertion
434 error.
435
436 :param serializer: serializer class or instance, or ``None``
437 :return: serializer class
438 :rtype: type[serializers.BaseSerializer]
439 """
440 if serializer is None:
441 return None
442
443 if inspect.isclass(serializer):
444 assert issubclass(serializer, serializers.BaseSerializer), (
445 "Serializer required, not %s" % serializer.__name__
446 )
447 return serializer
448
449 assert isinstance(serializer, serializers.BaseSerializer), (
450 "Serializer class or instance required, not %s" % type(serializer).__name__
451 )
452 return type(serializer)
453
454
455 def get_object_classes(classes_or_instances, expected_base_class=None):
456 """Given a list of instances or class objects, return the list of their classes.
457
458 :param classes_or_instances: mixed list to parse
459 :type classes_or_instances: list[type or object]
460 :param expected_base_class: if given, only subclasses or instances of this type will
461 be returned
462 :type expected_base_class: type
463 :return: list of classes
464 :rtype: list
465 """
466 classes_or_instances = classes_or_instances or []
467 result = []
468 for obj in classes_or_instances:
469 if inspect.isclass(obj):
470 if not expected_base_class or issubclass(obj, expected_base_class):
471 result.append(obj)
472 else:
473 if not expected_base_class or isinstance(obj, expected_base_class):
474 result.append(type(obj))
475
476 return result
477
478
479 def get_consumes(parser_classes):
480 """Extract ``consumes`` MIME types from a list of parser classes.
481
482 :param list parser_classes: parser classes
483 :type parser_classes: list[rest_framework.parsers.BaseParser or
484 type[rest_framework.parsers.BaseParser]]
485 :return: MIME types for ``consumes``
486 :rtype: list[str]
487 """
488 parser_classes = get_object_classes(parser_classes)
489 parser_classes = [
490 pc for pc in parser_classes if not issubclass(pc, FileUploadParser)
491 ]
492 media_types = [parser.media_type for parser in parser_classes or []]
493 non_form_media_types = [
494 encoding for encoding in media_types if not is_form_media_type(encoding)
495 ]
496 # Because swagger Parameter objects don't support complex data types
497 # (nested objects, arrays), we can't use those unless we are sure the view *only*
498 # accepts form data. This means that a view won't support file upload in swagger
499 # unless it explicitly sets its parser classes to include only form parsers
500 if len(non_form_media_types) == 0:
501 return media_types
502
503 # If the form accepts both form data and another type, like json (which is the
504 # default config), we will render its input as a Schema and thus it file parameters
505 # will be read-only
506 return non_form_media_types
507
508
509 def get_produces(renderer_classes):
510 """Extract ``produces`` MIME types from a list of renderer classes.
511
512 :param list renderer_classes: renderer classes
513 :type renderer_classes: list[rest_framework.renderers.BaseRenderer or
514 type[rest_framework.renderers.BaseRenderer]]
515 :return: MIME types for ``produces``
516 :rtype: list[str]
517 """
518 renderer_classes = get_object_classes(renderer_classes)
519 media_types = [renderer.media_type for renderer in renderer_classes or []]
520 media_types = [
521 encoding
522 for encoding in media_types
523 if not any(
524 excluded in encoding for excluded in swagger_settings.EXCLUDED_MEDIA_TYPES
525 )
526 ]
527 return media_types
528
529
530 def decimal_as_float(field):
531 """Returns true if ``field`` is a django-rest-framework DecimalField and its
532 ``coerce_to_string`` attribute or the ``COERCE_DECIMAL_TO_STRING`` setting is set to
533 ``False``.
534
535 :rtype: bool
536 """
537 if isinstance(field, serializers.DecimalField) or isinstance(
538 field, models.DecimalField
539 ):
540 return not getattr(
541 field, "coerce_to_string", rest_framework_settings.COERCE_DECIMAL_TO_STRING
542 )
543 return False
544
545
546 def get_serializer_ref_name(serializer):
547 """Get serializer's ref_name (or None for ModelSerializer if it is named
548 'NestedSerializer')
549
550 :param serializer: Serializer instance
551 :return: Serializer's ``ref_name`` or ``None`` for inline serializer
552 :rtype: str or None
553 """
554 serializer_meta = getattr(serializer, "Meta", None)
555 serializer_name = type(serializer).__name__
556 if hasattr(serializer_meta, "ref_name"):
557 ref_name = serializer_meta.ref_name
558 elif serializer_name == "NestedSerializer" and isinstance(
559 serializer, serializers.ModelSerializer
560 ):
561 logger.debug(
562 "Forcing inline output for ModelSerializer named 'NestedSerializer':\n"
563 + str(serializer)
564 )
565 ref_name = None
566 else:
567 ref_name = serializer_name
568 if ref_name.endswith("Serializer"):
569 ref_name = ref_name[: -len("Serializer")]
570 return ref_name
571
572
573 def force_real_str(s, encoding="utf-8", strings_only=False, errors="strict"):
574 """
575 Force `s` into a ``str`` instance.
576
577 Fix for https://github.com/axnsan12/drf-yasg/issues/159
578 """
579 if s is not None:
580 s = force_str(s, encoding, strings_only, errors)
581 if not isinstance(s, str):
582 s = "" + s
583
584 # Remove common indentation to get the correct Markdown rendering
585 s = textwrap.dedent(s)
586
587 return s
588
589
590 def field_value_to_representation(field, value):
591 """Convert a python value related to a field (default, choices, etc.) into its
592 OpenAPI-compatible representation.
593
594 :param serializers.Field field: field associated with the value
595 :param object value: value
596 :return: the converted value
597 """
598 value = field.to_representation(value)
599 if isinstance(value, Decimal):
600 if decimal_as_float(field):
601 value = float(value)
602 else:
603 value = str(value)
604
605 elif isinstance(value, pytz.BaseTzInfo):
606 value = str(value)
607
608 elif zoneinfo is not None and isinstance(value, zoneinfo.ZoneInfo):
609 value = str(value)
610
611 # JSON roundtrip ensures that the value is valid JSON;
612 # for example, sets and tuples get transformed into lists
613 return json.loads(json.dumps(value, cls=encoders.JSONEncoder))
614
615
616 def get_field_default(field):
617 """
618 Get the default value for a field, converted to a JSON-compatible value while
619 properly handling callables.
620
621 :param field: field instance
622 :return: default value
623 """
624 default = getattr(field, "default", serializers.empty)
625 if default is not serializers.empty:
626 if callable(default):
627 try:
628 if hasattr(default, "set_context"):
629 default.set_context(field)
630 if getattr(default, "requires_context", False):
631 default = default(field)
632 else:
633 default = default()
634 except Exception: # pragma: no cover
635 logger.warning(
636 "default for %s is callable but it raised an exception when "
637 "called; 'default' will not be set on schema",
638 field,
639 exc_info=True,
640 )
641 default = serializers.empty
642
643 if default is not serializers.empty and default is not None:
644 try:
645 default = field_value_to_representation(field, default)
646 except Exception: # pragma: no cover
647 logger.warning(
648 "'default' on schema for %s will not be set because "
649 "to_representation raised an exception",
650 field,
651 exc_info=True,
652 )
653 default = serializers.empty
654
655 return default