Debian Codegraph @

src/drf_yasg/inspectors/field.py

raw symbols SCIP
1 import datetime
2 import inspect
3 import logging
4 import operator
5 import sys
6 import typing
7 import uuid
8 import warnings
9 from contextlib import suppress
10 from decimal import Decimal
11
12 from django.core import validators
13 from django.db import models
14 from packaging import version
15 from rest_framework import serializers
16 from rest_framework.settings import api_settings as rest_framework_settings
17
18 from .. import openapi
19 from ..errors import SwaggerGenerationError
20 from ..utils import (
21 decimal_as_float,
22 field_value_to_representation,
23 filter_none,
24 get_serializer_class,
25 get_serializer_ref_name,
26 )
27 from .base import FieldInspector, NotHandled, SerializerInspector, call_view_method
28
29 try:
30 from importlib import metadata
31 except ImportError: # Python < 3.8
32 import importlib_metadata as metadata
33
34 drf_version = metadata.version("djangorestframework")
35
36 try:
37 from types import NoneType, UnionType
38
39 UNION_TYPES = (typing.Union, UnionType)
40 except ImportError: # Python < 3.10
41 NoneType = type(None)
42 UNION_TYPES = (typing.Union,)
43
44 DEFAULT_TYPE = openapi.TYPE_STRING
45
46 logger = logging.getLogger(__name__)
47
48
49 class InlineSerializerInspector(SerializerInspector):
50 """Provides serializer conversions using
51 :meth:`.FieldInspector.field_to_swagger_object`."""
52
53 #: whether to output :class:`.Schema` definitions inline or into the ``definitions``
54 # section
55 use_definitions = False
56
57 def get_schema(self, serializer):
58 return self.probe_field_inspectors(
59 serializer, openapi.Schema, self.use_definitions
60 )
61
62 def add_manual_parameters(self, serializer, parameters):
63 """Add/replace parameters from the given list of automatically generated request
64 parameters. This method is called only when the serializer is converted into a
65 list of parameters for use in a form data request.
66
67 :param serializer: serializer instance
68 :param list[openapi.Parameter] parameters: generated parameters
69 :return: modified parameters
70 :rtype: list[openapi.Parameter]
71 """
72 return parameters
73
74 def get_request_parameters(self, serializer, in_):
75 fields = getattr(serializer, "fields", {})
76 parameters = [
77 self.probe_field_inspectors(
78 value,
79 openapi.Parameter,
80 self.use_definitions,
81 name=self.get_parameter_name(key),
82 in_=in_,
83 )
84 for key, value in fields.items()
85 if not getattr(value, "read_only", False)
86 ]
87
88 return self.add_manual_parameters(serializer, parameters)
89
90 def get_property_name(self, field_name):
91 return field_name
92
93 def get_parameter_name(self, field_name):
94 return field_name
95
96 def get_serializer_ref_name(self, serializer):
97 return get_serializer_ref_name(serializer)
98
99 def _has_ref_name(self, serializer):
100 serializer_meta = getattr(serializer, "Meta", None)
101 return hasattr(serializer_meta, "ref_name")
102
103 def field_to_swagger_object(
104 self, field, swagger_object_type, use_references, **kwargs
105 ):
106 SwaggerType, ChildSwaggerType = self._get_partial_types(
107 field, swagger_object_type, use_references, **kwargs
108 )
109
110 if isinstance(field, (serializers.ListSerializer, serializers.ListField)):
111 child_schema = self.probe_field_inspectors(
112 field.child, ChildSwaggerType, use_references
113 )
114 limits = find_limits(field) or {}
115 return SwaggerType(type=openapi.TYPE_ARRAY, items=child_schema, **limits)
116 elif isinstance(field, serializers.Serializer):
117 if swagger_object_type != openapi.Schema:
118 raise SwaggerGenerationError(
119 "cannot instantiate nested serializer as "
120 + swagger_object_type.__name__
121 )
122
123 ref_name = self.get_serializer_ref_name(field)
124
125 def make_schema_definition(serializer=field):
126 properties = {}
127 required = []
128 for property_name, child in serializer.fields.items():
129 property_name = self.get_property_name(property_name)
130 prop_kwargs = {"read_only": bool(child.read_only) or None}
131 prop_kwargs = filter_none(prop_kwargs)
132
133 child_schema = self.probe_field_inspectors(
134 child, ChildSwaggerType, use_references, **prop_kwargs
135 )
136 properties[property_name] = child_schema
137
138 if child.required and not getattr(child_schema, "read_only", False):
139 required.append(property_name)
140
141 result = SwaggerType(
142 # the title is derived from the field name and is better to
143 # be omitted from models
144 use_field_title=False,
145 type=openapi.TYPE_OBJECT,
146 properties=properties,
147 required=required or None,
148 )
149
150 setattr(result, "_NP_serializer", get_serializer_class(serializer))
151 return result
152
153 if not ref_name or not use_references:
154 return make_schema_definition()
155
156 definitions = self.components.with_scope(openapi.SCHEMA_DEFINITIONS)
157 actual_schema = definitions.setdefault(ref_name, make_schema_definition)
158 actual_schema._remove_read_only()
159
160 actual_serializer = getattr(actual_schema, "_NP_serializer", None)
161 this_serializer = get_serializer_class(field)
162 if actual_serializer and actual_serializer != this_serializer:
163 explicit_refs = self._has_ref_name(
164 actual_serializer
165 ) and self._has_ref_name(this_serializer)
166 if not explicit_refs:
167 raise SwaggerGenerationError(
168 "Schema for %s would override distinct serializer %s because "
169 "they implicitly share the same ref_name; explicitly set the "
170 "ref_name attribute on both serializers' Meta classes"
171 % (actual_serializer, this_serializer)
172 )
173
174 return openapi.SchemaRef(definitions, ref_name)
175
176 return NotHandled
177
178
179 class ReferencingSerializerInspector(InlineSerializerInspector):
180 use_definitions = True
181
182
183 def get_queryset_field(queryset, field_name):
184 """Try to get information about a model and model field from a queryset.
185
186 :param queryset: the queryset
187 :param field_name: target field name
188 :returns: the model and target field from the queryset as a 2-tuple; both elements
189 can be ``None``
190 :rtype: tuple
191 """
192 model = getattr(queryset, "model", None)
193 model_field = get_model_field(model, field_name)
194 return model, model_field
195
196
197 def get_model_field(model, field_name):
198 """Try to get the given field from a django db model.
199
200 :param model: the model
201 :param field_name: target field name
202 :return: model field or ``None``
203 """
204 try:
205 if field_name == "pk":
206 return model._meta.pk
207 else:
208 return model._meta.get_field(field_name)
209 except Exception: # pragma: no cover
210 return None
211
212
213 def get_queryset_from_view(view, serializer=None):
214 """Try to get the queryset of the given view
215
216 :param view: the view instance or class
217 :param serializer: if given, will check that the view's get_serializer_class return
218 matches this serializer
219 :return: queryset or ``None``
220 """
221 try:
222 queryset = call_view_method(view, "get_queryset", "queryset")
223
224 if queryset is not None and serializer is not None:
225 # make sure the view is actually using *this* serializer
226 assert type(serializer) is call_view_method(
227 view, "get_serializer_class", "serializer_class"
228 )
229
230 return queryset
231 except Exception: # pragma: no cover
232 return None
233
234
235 def get_parent_serializer(field):
236 """Get the nearest parent ``Serializer`` instance for the given field.
237
238 :return: ``Serializer`` or ``None``
239 """
240 while field is not None:
241 if isinstance(field, serializers.Serializer):
242 return field
243
244 field = field.parent
245
246 return None # pragma: no cover
247
248
249 def get_model_from_descriptor(descriptor):
250 with suppress(Exception):
251 try:
252 return descriptor.rel.related_model
253 except Exception:
254 return descriptor.field.remote_field.model
255
256
257 def get_related_model(model, source):
258 """Try to find the other side of a model relationship given the name of a related
259 field.
260
261 :param model: one side of the relationship
262 :param str source: related field name
263 :return: related model or ``None``
264 """
265
266 with suppress(Exception):
267 if "." in source and source.index("."):
268 attr, source = source.split(".", maxsplit=1)
269 return get_related_model(
270 get_model_from_descriptor(getattr(model, attr)), source
271 )
272 return get_model_from_descriptor(getattr(model, source))
273
274
275 class RelatedFieldInspector(FieldInspector):
276 """Provides conversions for ``RelatedField``\\ s."""
277
278 def field_to_swagger_object(
279 self, field, swagger_object_type, use_references, **kwargs
280 ):
281 SwaggerType, ChildSwaggerType = self._get_partial_types(
282 field, swagger_object_type, use_references, **kwargs
283 )
284
285 if isinstance(field, serializers.ManyRelatedField):
286 child_schema = self.probe_field_inspectors(
287 field.child_relation, ChildSwaggerType, use_references
288 )
289 return SwaggerType(
290 type=openapi.TYPE_ARRAY,
291 items=child_schema,
292 unique_items=True,
293 )
294
295 if not isinstance(field, serializers.RelatedField):
296 return NotHandled
297
298 field_queryset = getattr(field, "queryset", None)
299
300 if isinstance(
301 field, (serializers.PrimaryKeyRelatedField, serializers.SlugRelatedField)
302 ):
303 if getattr(field, "pk_field", ""):
304 # a PrimaryKeyRelatedField can have a `pk_field` attribute which is a
305 # serializer field that will convert the PK value
306 result = self.probe_field_inspectors(
307 field.pk_field, swagger_object_type, use_references, **kwargs
308 )
309 # take the type, format, etc from `pk_field`, and the field-level
310 # information like title, description, default from the
311 # PrimaryKeyRelatedField
312 return SwaggerType(existing_object=result)
313
314 target_field = getattr(field, "slug_field", "pk")
315 if field_queryset is not None:
316 # if the RelatedField has a queryset, try to get the related model field
317 # from there
318 model, model_field = get_queryset_field(field_queryset, target_field)
319 else:
320 # if the RelatedField has no queryset (e.g. read only), try to find the
321 # target model from the view queryset or ModelSerializer model, if
322 # present
323 parent_serializer = get_parent_serializer(field)
324
325 serializer_meta = getattr(parent_serializer, "Meta", None)
326 this_model = getattr(serializer_meta, "model", None)
327 if not this_model:
328 view_queryset = get_queryset_from_view(self.view, parent_serializer)
329 this_model = getattr(view_queryset, "model", None)
330
331 source = getattr(field, "source", "") or field.field_name
332 if not source and isinstance(
333 field.parent, serializers.ManyRelatedField
334 ):
335 source = field.parent.field_name
336
337 model = get_related_model(this_model, source)
338 model_field = get_model_field(model, target_field)
339
340 attrs = get_basic_type_info(model_field) or {"type": DEFAULT_TYPE}
341 return SwaggerType(**attrs)
342 elif isinstance(field, serializers.HyperlinkedRelatedField):
343 return SwaggerType(type=openapi.TYPE_STRING, format=openapi.FORMAT_URI)
344
345 return NotHandled # pragma: no cover
346
347
348 def find_regex(regex_field):
349 """Given a ``Field``, look for a ``RegexValidator`` and try to extract its pattern
350 and return it as a string.
351
352 :param serializers.Field regex_field: the field instance
353 :return: the extracted pattern, or ``None``
354 :rtype: str
355 """
356 regex_validator = None
357 for validator in regex_field.validators:
358 if isinstance(validator, validators.RegexValidator):
359 if (
360 isinstance(validator, validators.URLValidator)
361 or validator == validators.validate_ipv4_address
362 ):
363 # skip the default url and IP regexes because they are complex and
364 # unhelpful validate_ipv4_address is a RegexValidator instance in
365 # Django 1.11
366 continue
367 if regex_validator is not None:
368 # bail if multiple validators are found - no obvious way to choose
369 return None # pragma: no cover
370 regex_validator = validator
371
372 # regex_validator.regex should be a compiled re object...
373 try:
374 pattern = getattr(getattr(regex_validator, "regex", None), "pattern", None)
375 except Exception: # pragma: no cover
376 logger.warning(
377 "failed to compile regex validator of " + str(regex_field), exc_info=True
378 )
379 return None
380
381 if pattern:
382 # attempt some basic cleanup to remove regex constructs not supported by
383 # JavaScript -- swagger uses javascript-style regexes
384 # see https://github.com/swagger-api/swagger-editor/issues/1601
385 if pattern.endswith("\\Z") or pattern.endswith("\\z"):
386 pattern = pattern[:-2] + "$"
387
388 return pattern
389
390
391 numeric_fields = (
392 serializers.IntegerField,
393 serializers.FloatField,
394 serializers.DecimalField,
395 )
396 limit_validators = [
397 # minimum and maximum apply to numbers
398 (validators.MinValueValidator, numeric_fields, "minimum", operator.__gt__),
399 (validators.MaxValueValidator, numeric_fields, "maximum", operator.__lt__),
400 # minLength and maxLength apply to strings
401 (
402 validators.MinLengthValidator,
403 serializers.CharField,
404 "min_length",
405 operator.__gt__,
406 ),
407 (
408 validators.MaxLengthValidator,
409 serializers.CharField,
410 "max_length",
411 operator.__lt__,
412 ),
413 # minItems and maxItems apply to lists
414 (
415 validators.MinLengthValidator,
416 (serializers.ListField, serializers.ListSerializer),
417 "min_items",
418 operator.__gt__,
419 ),
420 (
421 validators.MaxLengthValidator,
422 (serializers.ListField, serializers.ListSerializer),
423 "max_items",
424 operator.__lt__,
425 ),
426 ]
427
428
429 def find_limits(field):
430 """Given a ``Field``, look for min/max value/length validators and return
431 appropriate limit validation attributes.
432
433 :param serializers.Field field: the field instance
434 :return: the extracted limits
435 :rtype: dict
436 """
437 limits = {}
438 applicable_limits = [
439 (validator, attr, improves)
440 for validator, field_class, attr, improves in limit_validators
441 if isinstance(field, field_class)
442 ]
443
444 if isinstance(field, serializers.DecimalField) and not decimal_as_float(field):
445 return limits
446
447 for validator in field.validators:
448 if not hasattr(validator, "limit_value"):
449 continue
450
451 limit_value = validator.limit_value
452 if isinstance(limit_value, Decimal) and decimal_as_float(field):
453 limit_value = float(limit_value)
454
455 for validator_class, attr, improves in applicable_limits:
456 if isinstance(validator, validator_class):
457 if attr not in limits or improves(limit_value, limits[attr]):
458 limits[attr] = limit_value
459
460 if hasattr(field, "allow_blank") and not field.allow_blank:
461 if limits.get("min_length", 0) < 1:
462 limits["min_length"] = 1
463
464 return dict(sorted(limits.items()))
465
466
467 def decimal_field_type(field):
468 return openapi.TYPE_NUMBER if decimal_as_float(field) else openapi.TYPE_STRING
469
470
471 model_field_to_basic_type = [
472 (models.AutoField, (openapi.TYPE_INTEGER, None)),
473 (models.BinaryField, (openapi.TYPE_STRING, openapi.FORMAT_BINARY)),
474 (models.BooleanField, (openapi.TYPE_BOOLEAN, None)),
475 (models.DateTimeField, (openapi.TYPE_STRING, openapi.FORMAT_DATETIME)),
476 (models.DateField, (openapi.TYPE_STRING, openapi.FORMAT_DATE)),
477 (models.DecimalField, (decimal_field_type, openapi.FORMAT_DECIMAL)),
478 (models.DurationField, (openapi.TYPE_STRING, None)),
479 (models.FloatField, (openapi.TYPE_NUMBER, None)),
480 (models.IntegerField, (openapi.TYPE_INTEGER, None)),
481 (models.IPAddressField, (openapi.TYPE_STRING, openapi.FORMAT_IPV4)),
482 (models.GenericIPAddressField, (openapi.TYPE_STRING, openapi.FORMAT_IPV6)),
483 (models.SlugField, (openapi.TYPE_STRING, openapi.FORMAT_SLUG)),
484 (models.TextField, (openapi.TYPE_STRING, None)),
485 (models.TimeField, (openapi.TYPE_STRING, None)),
486 (models.UUIDField, (openapi.TYPE_STRING, openapi.FORMAT_UUID)),
487 (models.CharField, (openapi.TYPE_STRING, None)),
488 ]
489
490 ip_format = {"ipv4": openapi.FORMAT_IPV4, "ipv6": openapi.FORMAT_IPV6}
491
492 serializer_field_to_basic_type = [
493 (serializers.EmailField, (openapi.TYPE_STRING, openapi.FORMAT_EMAIL)),
494 (serializers.SlugField, (openapi.TYPE_STRING, openapi.FORMAT_SLUG)),
495 (serializers.URLField, (openapi.TYPE_STRING, openapi.FORMAT_URI)),
496 (
497 serializers.IPAddressField,
498 (openapi.TYPE_STRING, lambda field: ip_format.get(field.protocol, None)),
499 ),
500 (serializers.UUIDField, (openapi.TYPE_STRING, openapi.FORMAT_UUID)),
501 (serializers.RegexField, (openapi.TYPE_STRING, None)),
502 (serializers.CharField, (openapi.TYPE_STRING, None)),
503 (serializers.BooleanField, (openapi.TYPE_BOOLEAN, None)),
504 (serializers.IntegerField, (openapi.TYPE_INTEGER, None)),
505 (serializers.FloatField, (openapi.TYPE_NUMBER, None)),
506 (serializers.DecimalField, (decimal_field_type, openapi.FORMAT_DECIMAL)),
507 (serializers.DurationField, (openapi.TYPE_STRING, None)),
508 (serializers.DateField, (openapi.TYPE_STRING, openapi.FORMAT_DATE)),
509 (serializers.DateTimeField, (openapi.TYPE_STRING, openapi.FORMAT_DATETIME)),
510 (serializers.ModelField, (openapi.TYPE_STRING, None)),
511 ]
512
513 if version.parse(drf_version) < version.parse("3.14.0"):
514 model_field_to_basic_type.append(
515 (models.NullBooleanField, (openapi.TYPE_BOOLEAN, None))
516 )
517
518 serializer_field_to_basic_type.append(
519 (serializers.NullBooleanField, (openapi.TYPE_BOOLEAN, None)),
520 )
521
522 basic_type_info = serializer_field_to_basic_type + model_field_to_basic_type
523
524
525 def get_basic_type_info(field):
526 """Given a serializer or model ``Field``, return its basic type information -
527 ``type``, ``format``, ``pattern``, and any applicable min/max limit values.
528
529 :param field: the field instance
530 :return: the extracted attributes as a dictionary, or ``None`` if the field type is
531 not known
532 :rtype: dict
533 """
534 if field is None:
535 return None
536
537 for field_class, type_format in basic_type_info:
538 if isinstance(field, field_class):
539 swagger_type, format = type_format
540 if callable(swagger_type):
541 swagger_type = swagger_type(field)
542 if callable(format):
543 format = format(field)
544 break
545 else: # pragma: no cover
546 return None
547
548 pattern = None
549 if swagger_type == openapi.TYPE_STRING:
550 pattern = find_regex(field)
551
552 limits = find_limits(field)
553
554 result = {"type": swagger_type, "format": format, "pattern": pattern}
555 result.update(limits)
556 result = filter_none(result)
557 return result
558
559
560 def decimal_return_type():
561 return (
562 openapi.TYPE_STRING
563 if rest_framework_settings.COERCE_DECIMAL_TO_STRING
564 else openapi.TYPE_NUMBER
565 )
566
567
568 hinting_type_info = [
569 (bool, (openapi.TYPE_BOOLEAN, None)),
570 (int, (openapi.TYPE_INTEGER, None)),
571 (str, (openapi.TYPE_STRING, None)),
572 (float, (openapi.TYPE_NUMBER, None)),
573 (dict, (openapi.TYPE_OBJECT, None)),
574 (Decimal, (decimal_return_type, openapi.FORMAT_DECIMAL)),
575 (uuid.UUID, (openapi.TYPE_STRING, openapi.FORMAT_UUID)),
576 (datetime.datetime, (openapi.TYPE_STRING, openapi.FORMAT_DATETIME)),
577 (datetime.date, (openapi.TYPE_STRING, openapi.FORMAT_DATE)),
578 ]
579
580
581 if hasattr(typing, "get_args"):
582 # python >=3.8
583 typing_get_args = typing.get_args
584 typing_get_origin = typing.get_origin
585 else:
586 # python <3.8
587 def typing_get_args(tp):
588 return getattr(tp, "__args__", ())
589
590 def typing_get_origin(tp):
591 return getattr(tp, "__origin__", None)
592
593
594 def inspect_collection_hint_class(hint_class):
595 args = typing_get_args(hint_class)
596 child_class = args[0] if args else str
597 child_type_info = get_basic_type_info_from_hint(child_class) or {
598 "type": DEFAULT_TYPE
599 }
600
601 return {"type": openapi.TYPE_ARRAY, "items": openapi.Items(**child_type_info)}
602
603
604 hinting_type_info.extend(
605 [((typing.Sequence, typing.AbstractSet), inspect_collection_hint_class)]
606 + ([(typing.Any, (DEFAULT_TYPE, None))] if sys.version_info >= (3, 11) else [])
607 )
608
609
610 def get_basic_type_info_from_hint(hint_class):
611 """Given a class (eg from a SerializerMethodField's return type hint,
612 return its basic type information - ``type``, ``format``, ``pattern``,
613 and any applicable min/max limit values.
614
615 :param hint_class: the class
616 :return: the extracted attributes as a dictionary, or ``None`` if the field type is
617 not known
618 :rtype: dict
619 """
620
621 if typing_get_origin(hint_class) in UNION_TYPES:
622 # Optional is implemented as Union[T, None]
623 filtered_types = [t for t in typing_get_args(hint_class) if t is not NoneType]
624 if len(filtered_types) == 1:
625 result = get_basic_type_info_from_hint(filtered_types[0])
626 if result:
627 result["x-nullable"] = True
628
629 return result
630
631 return None
632
633 # resolve the origin class if the class is generic
634 resolved_class = typing_get_origin(hint_class) or hint_class
635
636 # `typing.Any` is not represented as a class until Python 3.11
637 if sys.version_info < (3, 11) and resolved_class is typing.Any:
638 return {"type": DEFAULT_TYPE}
639
640 # bail out early
641 if not inspect.isclass(resolved_class):
642 return None
643
644 for check_class, info in hinting_type_info:
645 if issubclass(resolved_class, check_class):
646 if callable(info):
647 return info(hint_class)
648
649 swagger_type, format = info
650 if callable(swagger_type):
651 swagger_type = swagger_type()
652
653 return {"type": swagger_type, "format": format}
654
655 return None
656
657
658 class SerializerMethodFieldInspector(FieldInspector):
659 """Provides conversion for SerializerMethodField, optionally using information from
660 the swagger_serializer_method decorator.
661 """
662
663 def field_to_swagger_object( # noqa: C901
664 self, field, swagger_object_type, use_references, **kwargs
665 ):
666 if not isinstance(field, serializers.SerializerMethodField):
667 return NotHandled
668
669 def method_path() -> str:
670 return f"""{field.parent.__class__.__module__}.{
671 field.parent.__class__.__qualname__
672 }.{field.method_name}"""
673
674 method = getattr(field.parent, field.method_name, None)
675 if method is None:
676 warnings.warn(
677 f"SerializerMethodField method {method_path()} does not exist!"
678 )
679 return NotHandled
680
681 # attribute added by the swagger_serializer_method decorator
682 serializer = getattr(method, "_swagger_serializer", None)
683
684 if serializer:
685 # in order of preference for description, use:
686 # 1) field.help_text from SerializerMethodField(help_text)
687 # 2) serializer.help_text from swagger_serializer_method(serializer)
688 # 3) method's docstring
689 description = field.help_text
690 if description is None:
691 description = getattr(serializer, "help_text", None)
692 if description is None:
693 description = method.__doc__
694
695 label = field.label
696 if label is None:
697 label = getattr(serializer, "label", None)
698
699 if inspect.isclass(serializer):
700 serializer_kwargs = {
701 "help_text": description,
702 "label": label,
703 "read_only": True,
704 }
705
706 serializer = method._swagger_serializer(**serializer_kwargs)
707 else:
708 serializer.help_text = description
709 serializer.label = label
710 serializer.read_only = True
711
712 return self.probe_field_inspectors(
713 serializer, swagger_object_type, use_references, read_only=True
714 )
715 else:
716 # look for Python 3.5+ style type hinting of the return value
717 annotations = {"return": typing.Any}
718 return_annotation = inspect.signature(method).return_annotation
719
720 try:
721 if return_annotation is not inspect._empty:
722 annotations = typing.get_type_hints(method)
723 except NameError:
724 # try handling forward references with Python 3.12 type parameters
725 # (PEP-695), which are not defined in the module scope and will not
726 # resolve if postponed evaluation of annotations (PEP-563) is enabled.
727 localns = {
728 t.__name__: t
729 # include any class or method type parameters
730 for scope in (field.parent, method)
731 for t in getattr(scope, "__type_params__", ())
732 }
733 module_name = field.parent.__module__
734
735 try:
736 # bail if there are no type parameters or the module isn't loaded
737 if not localns or module_name not in sys.modules:
738 raise
739
740 annotations = typing.get_type_hints(
741 method, vars(sys.modules[module_name]), localns
742 )
743 except NameError:
744 warnings.warn(
745 f"Cannot resolve return annotation: {return_annotation!r} "
746 f"({method_path()}); Is this expression not imported, or only "
747 "imported in a TYPE_CHECKING block? Use "
748 "`swagger_serializer_method` to define the return type."
749 )
750
751 hint_class = annotations.get("return")
752 if hint_class is None:
753 warnings.warn(
754 f"{method_path()} has no return type annotation and is not "
755 "decorated with `swagger_serializer_method`; "
756 "Using `Any` as its return type."
757 )
758 hint_class = typing.Any
759
760 type_info = get_basic_type_info_from_hint(hint_class)
761 if type_info is None:
762 warnings.warn(
763 f"Cannot coerce return annotation {return_annotation!r} from "
764 f"{method_path()} to any valid type; Using `Any` as its return "
765 "type. Use `swagger_serializer_method` to change this behavior."
766 )
767 type_info = get_basic_type_info_from_hint(typing.Any)
768
769 SwaggerType, ChildSwaggerType = self._get_partial_types(
770 field, swagger_object_type, use_references, **kwargs
771 )
772 return SwaggerType(**type_info)
773
774 return NotHandled
775
776
777 class SimpleFieldInspector(FieldInspector):
778 """Provides conversions for fields which can be described using just ``type``,
779 ``format``, ``pattern`` and min/max validators.
780 """
781
782 def field_to_swagger_object(
783 self, field, swagger_object_type, use_references, **kwargs
784 ):
785 type_info = get_basic_type_info(field)
786 if type_info is None:
787 return NotHandled
788
789 SwaggerType, ChildSwaggerType = self._get_partial_types(
790 field, swagger_object_type, use_references, **kwargs
791 )
792 return SwaggerType(**type_info)
793
794
795 class ChoiceFieldInspector(FieldInspector):
796 """Provides conversions for ``ChoiceField`` and ``MultipleChoiceField``."""
797
798 def field_to_swagger_object(
799 self, field, swagger_object_type, use_references, **kwargs
800 ):
801 SwaggerType, ChildSwaggerType = self._get_partial_types(
802 field, swagger_object_type, use_references, **kwargs
803 )
804
805 if isinstance(field, serializers.ChoiceField):
806 enum_type = openapi.TYPE_STRING
807 enum_values = []
808 for choice in field.choices.keys():
809 if isinstance(field, serializers.MultipleChoiceField):
810 choice = field_value_to_representation(field, [choice])[0]
811 else:
812 choice = field_value_to_representation(field, choice)
813
814 enum_values.append(choice)
815
816 # for ModelSerializer, try to infer the type from the associated model field
817 serializer = get_parent_serializer(field)
818 if isinstance(serializer, serializers.ModelSerializer):
819 model = getattr(getattr(serializer, "Meta"), "model")
820 # Use the parent source for nested fields
821 model_field = get_model_field(
822 model, field.source or field.parent.source
823 )
824 # If the field has a base_field its type must be used
825 if getattr(model_field, "base_field", None):
826 model_field = model_field.base_field
827 if model_field:
828 model_type = get_basic_type_info(model_field)
829 if model_type:
830 enum_type = model_type.get("type", enum_type)
831 else:
832 # Try to infer field type based on enum values
833 enum_value_types = {type(v) for v in enum_values}
834 if len(enum_value_types) == 1:
835 values_type = get_basic_type_info_from_hint(
836 next(iter(enum_value_types))
837 )
838 if values_type:
839 enum_type = values_type.get("type", enum_type)
840
841 if isinstance(field, serializers.MultipleChoiceField):
842 result = SwaggerType(
843 type=openapi.TYPE_ARRAY,
844 items=ChildSwaggerType(type=enum_type, enum=enum_values),
845 )
846 if swagger_object_type == openapi.Parameter:
847 if result["in"] in (openapi.IN_FORM, openapi.IN_QUERY):
848 result.collection_format = "multi"
849 else:
850 result = SwaggerType(type=enum_type, enum=enum_values)
851
852 return result
853
854 return NotHandled
855
856
857 class FileFieldInspector(FieldInspector):
858 """Provides conversions for ``FileField``\\ s."""
859
860 def field_to_swagger_object(
861 self, field, swagger_object_type, use_references, **kwargs
862 ):
863 SwaggerType, ChildSwaggerType = self._get_partial_types(
864 field, swagger_object_type, use_references, **kwargs
865 )
866
867 if isinstance(field, serializers.FileField):
868 # swagger 2.0 does not support specifics about file fields, so ImageFile
869 # gets no special treatment OpenAPI 3.0 does support it, so a future
870 # implementation could handle this better
871 err = SwaggerGenerationError(
872 "FileField is supported only in a formData Parameter or response Schema"
873 )
874 if swagger_object_type == openapi.Schema:
875 # FileField.to_representation returns URL or file name
876 result = SwaggerType(type=openapi.TYPE_STRING, read_only=True)
877 if getattr(
878 field, "use_url", rest_framework_settings.UPLOADED_FILES_USE_URL
879 ):
880 result.format = openapi.FORMAT_URI
881 return result
882 elif swagger_object_type == openapi.Parameter:
883 param = SwaggerType(type=openapi.TYPE_FILE)
884 if param["in"] != openapi.IN_FORM:
885 raise err # pragma: no cover
886 return param
887 else:
888 raise err # pragma: no cover
889
890 return NotHandled
891
892
893 class DictFieldInspector(FieldInspector):
894 """Provides conversion for ``DictField``."""
895
896 def field_to_swagger_object(
897 self, field, swagger_object_type, use_references, **kwargs
898 ):
899 SwaggerType, ChildSwaggerType = self._get_partial_types(
900 field, swagger_object_type, use_references, **kwargs
901 )
902
903 if (
904 isinstance(field, serializers.DictField)
905 and swagger_object_type == openapi.Schema
906 ):
907 child_schema = self.probe_field_inspectors(
908 field.child, ChildSwaggerType, use_references
909 )
910 return SwaggerType(
911 type=openapi.TYPE_OBJECT, additional_properties=child_schema
912 )
913
914 return NotHandled
915
916
917 class HiddenFieldInspector(FieldInspector):
918 """Hide ``HiddenField``."""
919
920 def field_to_swagger_object(
921 self, field, swagger_object_type, use_references, **kwargs
922 ):
923 if isinstance(field, serializers.HiddenField):
924 return None
925
926 return NotHandled
927
928
929 class JSONFieldInspector(FieldInspector):
930 """Provides conversion for ``JSONField``."""
931
932 def field_to_swagger_object(
933 self, field, swagger_object_type, use_references, **kwargs
934 ):
935 SwaggerType, ChildSwaggerType = self._get_partial_types(
936 field, swagger_object_type, use_references, **kwargs
937 )
938
939 if (
940 isinstance(field, serializers.JSONField)
941 and swagger_object_type == openapi.Schema
942 ):
943 return SwaggerType(type=openapi.TYPE_OBJECT)
944
945 return NotHandled
946
947
948 class StringDefaultFieldInspector(FieldInspector):
949 """For otherwise unhandled fields, return them as plain :data:`.TYPE_STRING`
950 objects."""
951
952 def field_to_swagger_object(
953 self, field, swagger_object_type, use_references, **kwargs
954 ): # pragma: no cover
955 # TODO unhandled fields: TimeField
956 SwaggerType, ChildSwaggerType = self._get_partial_types(
957 field, swagger_object_type, use_references, **kwargs
958 )
959 return SwaggerType(type=DEFAULT_TYPE)
960
961
962 try:
963 from djangorestframework_camel_case.parser import CamelCaseJSONParser
964 from djangorestframework_camel_case.render import CamelCaseJSONRenderer, camelize
965 except ImportError: # pragma: no cover
966 CamelCaseJSONParser = CamelCaseJSONRenderer = None
967
968 def camelize(data):
969 return data
970
971
972 class CamelCaseJSONFilter(FieldInspector):
973 """Converts property names to camelCase if ``djangorestframework_camel_case`` is
974 used."""
975
976 def camelize_string(self, s):
977 """Hack to force ``djangorestframework_camel_case`` to camelize a plain string.
978
979 :param str s: the string
980 :return: camelized string
981 :rtype: str
982 """
983 return next(iter(camelize({s: ""})))
984
985 def camelize_schema(self, schema):
986 """Recursively camelize property names for the given schema using
987 ``djangorestframework_camel_case``.
988 The target schema object must be modified in-place.
989
990 :param openapi.Schema schema: the :class:`.Schema` object
991 """
992 if getattr(schema, "properties", {}):
993 schema.properties = {
994 self.camelize_string(key): self.camelize_schema(
995 openapi.resolve_ref(val, self.components)
996 )
997 or val
998 for key, val in schema.properties.items()
999 }
1000
1001 if getattr(schema, "required", []):
1002 schema.required = [self.camelize_string(p) for p in schema.required]
1003
1004 def process_result(self, result, method_name, obj, **kwargs):
1005 if isinstance(result, openapi.Schema.OR_REF) and self.is_camel_case():
1006 schema = openapi.resolve_ref(result, self.components)
1007 self.camelize_schema(schema)
1008
1009 return result
1010
1011 if CamelCaseJSONParser and CamelCaseJSONRenderer:
1012
1013 def is_camel_case(self):
1014 return any(
1015 issubclass(parser, CamelCaseJSONParser)
1016 for parser in self.get_parser_classes()
1017 ) or any(
1018 issubclass(renderer, CamelCaseJSONRenderer)
1019 for renderer in self.get_renderer_classes()
1020 )
1021 else:
1022
1023 def is_camel_case(self):
1024 return False
1025
1026
1027 try:
1028 from rest_framework_recursive.fields import RecursiveField
1029 except ImportError: # pragma: no cover
1030
1031 class RecursiveFieldInspector(FieldInspector):
1032 """Provides conversion for RecursiveField (https://github.com/heywbj/django-rest-framework-recursive)"""
1033
1034 pass
1035 else:
1036
1037 class RecursiveFieldInspector(FieldInspector):
1038 """Provides conversion for RecursiveField (https://github.com/heywbj/django-rest-framework-recursive)"""
1039
1040 def field_to_swagger_object(
1041 self, field, swagger_object_type, use_references, **kwargs
1042 ):
1043 if (
1044 isinstance(field, RecursiveField)
1045 and swagger_object_type == openapi.Schema
1046 ):
1047 assert use_references is True, (
1048 "Can not create schema for RecursiveField when use_references is "
1049 "False"
1050 )
1051
1052 proxied = field.proxied
1053 if isinstance(field.proxied, serializers.ListSerializer):
1054 proxied = proxied.child
1055
1056 ref_name = get_serializer_ref_name(proxied)
1057 assert ref_name is not None, (
1058 "Can't create RecursiveField schema for inline "
1059 + str(type(proxied))
1060 )
1061
1062 definitions = self.components.with_scope(openapi.SCHEMA_DEFINITIONS)
1063
1064 ref = openapi.SchemaRef(definitions, ref_name, ignore_unresolved=True)
1065 if isinstance(field.proxied, serializers.ListSerializer):
1066 ref = openapi.Items(type=openapi.TYPE_ARRAY, items=ref)
1067
1068 return ref
1069
1070 return NotHandled