schema.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. import re
  2. import typing
  3. from collections import OrderedDict
  4. from drf_spectacular.extensions import OpenApiSerializerFieldExtension
  5. from drf_spectacular.openapi import AutoSchema
  6. from drf_spectacular.plumbing import (
  7. build_basic_type, build_choice_field, build_media_type_object, build_object_type, get_doc,
  8. )
  9. from drf_spectacular.types import OpenApiTypes
  10. from netbox.api.fields import ChoiceField
  11. from netbox.api.serializers import WritableNestedSerializer
  12. # see netbox.api.routers.NetBoxRouter
  13. BULK_ACTIONS = ("bulk_destroy", "bulk_partial_update", "bulk_update")
  14. WRITABLE_ACTIONS = ("PATCH", "POST", "PUT")
  15. class FixTimeZoneSerializerField(OpenApiSerializerFieldExtension):
  16. target_class = 'timezone_field.rest_framework.TimeZoneSerializerField'
  17. def map_serializer_field(self, auto_schema, direction):
  18. return build_basic_type(OpenApiTypes.STR)
  19. class ChoiceFieldFix(OpenApiSerializerFieldExtension):
  20. target_class = 'netbox.api.fields.ChoiceField'
  21. def map_serializer_field(self, auto_schema, direction):
  22. build_cf = build_choice_field(self.target)
  23. if direction == 'request':
  24. return build_cf
  25. elif direction == "response":
  26. value = build_cf
  27. label = {
  28. **build_basic_type(OpenApiTypes.STR),
  29. "enum": list(OrderedDict.fromkeys(self.target.choices.values()))
  30. }
  31. return build_object_type(
  32. properties={
  33. "value": value,
  34. "label": label
  35. }
  36. )
  37. class NetBoxAutoSchema(AutoSchema):
  38. """
  39. Overrides to drf_spectacular.openapi.AutoSchema to fix following issues:
  40. 1. bulk serializers cause operation_id conflicts with non-bulk ones
  41. 2. bulk operations should specify a list
  42. 3. bulk operations don't have filter params
  43. 4. bulk operations don't have pagination
  44. 5. bulk delete should specify input
  45. """
  46. writable_serializers = {}
  47. @property
  48. def is_bulk_action(self):
  49. if hasattr(self.view, "action") and self.view.action in BULK_ACTIONS:
  50. return True
  51. else:
  52. return False
  53. def get_operation_id(self):
  54. """
  55. bulk serializers cause operation_id conflicts with non-bulk ones
  56. bulk operations cause id conflicts in spectacular resulting in numerous:
  57. Warning: operationId "xxx" has collisions [xxx]. "resolving with numeral suffixes"
  58. code is modified from drf_spectacular.openapi.AutoSchema.get_operation_id
  59. """
  60. if self.is_bulk_action:
  61. tokenized_path = self._tokenize_path()
  62. # replace dashes as they can be problematic later in code generation
  63. tokenized_path = [t.replace('-', '_') for t in tokenized_path]
  64. if self.method == 'GET' and self._is_list_view():
  65. # this shouldn't happen, but keeping it here to follow base code
  66. action = 'list'
  67. else:
  68. # action = self.method_mapping[self.method.lower()]
  69. # use bulk name so partial_update -> bulk_partial_update
  70. action = self.view.action.lower()
  71. if not tokenized_path:
  72. tokenized_path.append('root')
  73. if re.search(r'<drf_format_suffix\w*:\w+>', self.path_regex):
  74. tokenized_path.append('formatted')
  75. return '_'.join(tokenized_path + [action])
  76. # if not bulk - just return normal id
  77. return super().get_operation_id()
  78. def get_request_serializer(self) -> typing.Any:
  79. # bulk operations should specify a list
  80. serializer = super().get_request_serializer()
  81. if self.is_bulk_action:
  82. return type(serializer)(many=True)
  83. # handle mapping for Writable serializers - adapted from dansheps original code
  84. # for drf-yasg
  85. if serializer is not None and self.method in WRITABLE_ACTIONS:
  86. writable_class = self.get_writable_class(serializer)
  87. if writable_class is not None:
  88. if hasattr(serializer, "child"):
  89. child_serializer = self.get_writable_class(serializer.child)
  90. serializer = writable_class(context=serializer.context, child=child_serializer)
  91. else:
  92. serializer = writable_class(context=serializer.context)
  93. return serializer
  94. def get_response_serializers(self) -> typing.Any:
  95. # bulk operations should specify a list
  96. response_serializers = super().get_response_serializers()
  97. if self.is_bulk_action:
  98. return type(response_serializers)(many=True)
  99. return response_serializers
  100. def _get_serializer_name(self, serializer, direction, bypass_extensions=False) -> str:
  101. name = super()._get_serializer_name(serializer, direction, bypass_extensions)
  102. # If this serializer is nested, prepend its name with "Brief"
  103. if getattr(serializer, 'nested', False):
  104. name = f'Brief{name}'
  105. return name
  106. def get_serializer_ref_name(self, serializer):
  107. # from drf-yasg.utils
  108. """Get serializer's ref_name
  109. :param serializer: Serializer instance
  110. :return: Serializer's ``ref_name`` or ``None`` for inline serializer
  111. :rtype: str or None
  112. """
  113. serializer_meta = getattr(serializer, 'Meta', None)
  114. serializer_name = type(serializer).__name__
  115. if hasattr(serializer_meta, 'ref_name'):
  116. ref_name = serializer_meta.ref_name
  117. else:
  118. ref_name = serializer_name
  119. if ref_name.endswith('Serializer'):
  120. ref_name = ref_name[: -len('Serializer')]
  121. return ref_name
  122. def get_writable_class(self, serializer):
  123. properties = {}
  124. fields = {} if hasattr(serializer, 'child') else serializer.fields
  125. remove_fields = []
  126. # If you get a failure here for "AttributeError: 'cached_property' object has no attribute 'items'"
  127. # it is probably because you are using a viewsets.ViewSet for the API View and are defining a
  128. # serializer_class. You will also need to define a get_serializer() method like for GenericAPIView.
  129. for child_name, child in fields.items():
  130. # read_only fields don't need to be in writable (write only) serializers
  131. if 'read_only' in dir(child) and child.read_only:
  132. remove_fields.append(child_name)
  133. if isinstance(child, (ChoiceField, WritableNestedSerializer)):
  134. properties[child_name] = None
  135. if not properties:
  136. return None
  137. if type(serializer) not in self.writable_serializers:
  138. writable_name = 'Writable' + type(serializer).__name__
  139. meta_class = getattr(type(serializer), 'Meta', None)
  140. if meta_class:
  141. ref_name = 'Writable' + self.get_serializer_ref_name(serializer)
  142. # remove read_only fields from write-only serializers
  143. fields = list(meta_class.fields)
  144. for field in remove_fields:
  145. fields.remove(field)
  146. writable_meta = type('Meta', (meta_class,), {'ref_name': ref_name, 'fields': fields})
  147. properties['Meta'] = writable_meta
  148. self.writable_serializers[type(serializer)] = type(writable_name, (type(serializer),), properties)
  149. writable_class = self.writable_serializers[type(serializer)]
  150. return writable_class
  151. def get_filter_backends(self):
  152. # bulk operations don't have filter params
  153. if self.is_bulk_action:
  154. return []
  155. return super().get_filter_backends()
  156. def _get_paginator(self):
  157. # bulk operations don't have pagination
  158. if self.is_bulk_action:
  159. return None
  160. return super()._get_paginator()
  161. def _get_request_body(self, direction='request'):
  162. # bulk delete should specify input
  163. if (not self.is_bulk_action) or (self.method != 'DELETE'):
  164. return super()._get_request_body(direction)
  165. # rest from drf_spectacular.openapi.AutoSchema._get_request_body
  166. # but remove the unsafe method check
  167. request_serializer = self.get_request_serializer()
  168. if isinstance(request_serializer, dict):
  169. content = []
  170. request_body_required = True
  171. for media_type, serializer in request_serializer.items():
  172. schema, partial_request_body_required = self._get_request_for_media_type(serializer, direction)
  173. examples = self._get_examples(serializer, direction, media_type)
  174. if schema is None:
  175. continue
  176. content.append((media_type, schema, examples))
  177. request_body_required &= partial_request_body_required
  178. else:
  179. schema, request_body_required = self._get_request_for_media_type(request_serializer, direction)
  180. if schema is None:
  181. return None
  182. content = [
  183. (media_type, schema, self._get_examples(request_serializer, direction, media_type))
  184. for media_type in self.map_parsers()
  185. ]
  186. request_body = {
  187. 'content': {
  188. media_type: build_media_type_object(schema, examples) for media_type, schema, examples in content
  189. }
  190. }
  191. if request_body_required:
  192. request_body['required'] = request_body_required
  193. return request_body
  194. def get_description(self):
  195. """
  196. Return a string description for the ViewSet.
  197. """
  198. # If a docstring is provided, use it.
  199. if self.view.__doc__:
  200. return get_doc(self.view.__class__)
  201. # When the action method is decorated with @action, use the docstring of the method.
  202. action_or_method = getattr(self.view, getattr(self.view, 'action', self.method.lower()), None)
  203. if action_or_method and action_or_method.__doc__:
  204. return get_doc(action_or_method)
  205. # Else, generate a description from the class name.
  206. return self._generate_description()
  207. def _generate_description(self):
  208. """
  209. Generate a docstring for the method. It also takes into account whether the method is for list or detail.
  210. """
  211. model_name = self.view.queryset.model._meta.verbose_name
  212. # Determine if the method is for list or detail.
  213. if '{id}' in self.path:
  214. return f"{self.method.capitalize()} a {model_name} object."
  215. return f"{self.method.capitalize()} a list of {model_name} objects."
  216. class FixSerializedPKRelatedField(OpenApiSerializerFieldExtension):
  217. target_class = 'netbox.api.fields.SerializedPKRelatedField'
  218. def map_serializer_field(self, auto_schema, direction):
  219. if direction == "response":
  220. component = auto_schema.resolve_serializer(self.target.serializer, direction)
  221. return component.ref if component else None
  222. else:
  223. return build_basic_type(OpenApiTypes.INT)