| 1 |
import re |
| 2 |
import warnings |
| 3 |
from decimal import Decimal |
| 4 |
from operator import attrgetter |
| 5 |
from urllib.parse import urljoin |
| 6 |
|
| 7 |
from django.core.validators import ( |
| 8 |
DecimalValidator, EmailValidator, MaxLengthValidator, MaxValueValidator, |
| 9 |
MinLengthValidator, MinValueValidator, RegexValidator, URLValidator |
| 10 |
) |
| 11 |
from django.db import models |
| 12 |
from django.utils.encoding import force_str |
| 13 |
|
| 14 |
from rest_framework import exceptions, renderers, serializers |
| 15 |
from rest_framework.compat import inflection, uritemplate |
| 16 |
from rest_framework.fields import _UnvalidatedField, empty |
| 17 |
from rest_framework.settings import api_settings |
| 18 |
|
| 19 |
from .generators import BaseSchemaGenerator |
| 20 |
from .inspectors import ViewInspector |
| 21 |
from .utils import get_pk_description, is_list_view |
| 22 |
|
| 23 |
|
| 24 |
class SchemaGenerator(BaseSchemaGenerator): |
| 25 |
|
| 26 |
def get_info(self): |
| 27 |
# Title and version are required by openapi specification 3.x |
| 28 |
info = { |
| 29 |
'title': self.title or '', |
| 30 |
'version': self.version or '' |
| 31 |
} |
| 32 |
|
| 33 |
if self.description is not None: |
| 34 |
info['description'] = self.description |
| 35 |
|
| 36 |
return info |
| 37 |
|
| 38 |
def check_duplicate_operation_id(self, paths): |
| 39 |
ids = {} |
| 40 |
for route in paths: |
| 41 |
for method in paths[route]: |
| 42 |
if 'operationId' not in paths[route][method]: |
| 43 |
continue |
| 44 |
operation_id = paths[route][method]['operationId'] |
| 45 |
if operation_id in ids: |
| 46 |
warnings.warn( |
| 47 |
'You have a duplicated operationId in your OpenAPI schema: {operation_id}\n' |
| 48 |
'\tRoute: {route1}, Method: {method1}\n' |
| 49 |
'\tRoute: {route2}, Method: {method2}\n' |
| 50 |
'\tAn operationId has to be unique across your schema. Your schema may not work in other tools.' |
| 51 |
.format( |
| 52 |
route1=ids[operation_id]['route'], |
| 53 |
method1=ids[operation_id]['method'], |
| 54 |
route2=route, |
| 55 |
method2=method, |
| 56 |
operation_id=operation_id |
| 57 |
) |
| 58 |
) |
| 59 |
ids[operation_id] = { |
| 60 |
'route': route, |
| 61 |
'method': method |
| 62 |
} |
| 63 |
|
| 64 |
def get_schema(self, request=None, public=False): |
| 65 |
""" |
| 66 |
Generate a OpenAPI schema. |
| 67 |
""" |
| 68 |
self._initialise_endpoints() |
| 69 |
components_schemas = {} |
| 70 |
|
| 71 |
# Iterate endpoints generating per method path operations. |
| 72 |
paths = {} |
| 73 |
_, view_endpoints = self._get_paths_and_endpoints(None if public else request) |
| 74 |
for path, method, view in view_endpoints: |
| 75 |
if not self.has_view_permissions(path, method, view): |
| 76 |
continue |
| 77 |
|
| 78 |
operation = view.schema.get_operation(path, method) |
| 79 |
components = view.schema.get_components(path, method) |
| 80 |
for k in components.keys(): |
| 81 |
if k not in components_schemas: |
| 82 |
continue |
| 83 |
if components_schemas[k] == components[k]: |
| 84 |
continue |
| 85 |
warnings.warn(f'Schema component "{k}" has been overridden with a different value.') |
| 86 |
|
| 87 |
components_schemas.update(components) |
| 88 |
|
| 89 |
# Normalize path for any provided mount url. |
| 90 |
if path.startswith('/'): |
| 91 |
path = path[1:] |
| 92 |
path = urljoin(self.url or '/', path) |
| 93 |
|
| 94 |
paths.setdefault(path, {}) |
| 95 |
paths[path][method.lower()] = operation |
| 96 |
|
| 97 |
self.check_duplicate_operation_id(paths) |
| 98 |
|
| 99 |
# Compile final schema. |
| 100 |
schema = { |
| 101 |
'openapi': '3.0.2', |
| 102 |
'info': self.get_info(), |
| 103 |
'paths': paths, |
| 104 |
} |
| 105 |
|
| 106 |
if len(components_schemas) > 0: |
| 107 |
schema['components'] = { |
| 108 |
'schemas': components_schemas |
| 109 |
} |
| 110 |
|
| 111 |
return schema |
| 112 |
|
| 113 |
# View Inspectors |
| 114 |
|
| 115 |
|
| 116 |
class AutoSchema(ViewInspector): |
| 117 |
|
| 118 |
def __init__(self, tags=None, operation_id_base=None, component_name=None): |
| 119 |
""" |
| 120 |
:param operation_id_base: user-defined name in operationId. If empty, it will be deducted from the Model/Serializer/View name. |
| 121 |
:param component_name: user-defined component's name. If empty, it will be deducted from the Serializer's class name. |
| 122 |
""" |
| 123 |
if tags and not all(isinstance(tag, str) for tag in tags): |
| 124 |
raise ValueError('tags must be a list or tuple of string.') |
| 125 |
self._tags = tags |
| 126 |
self.operation_id_base = operation_id_base |
| 127 |
self.component_name = component_name |
| 128 |
super().__init__() |
| 129 |
|
| 130 |
request_media_types = [] |
| 131 |
response_media_types = [] |
| 132 |
|
| 133 |
method_mapping = { |
| 134 |
'get': 'retrieve', |
| 135 |
'post': 'create', |
| 136 |
'put': 'update', |
| 137 |
'patch': 'partialUpdate', |
| 138 |
'delete': 'destroy', |
| 139 |
} |
| 140 |
|
| 141 |
def get_operation(self, path, method): |
| 142 |
operation = {} |
| 143 |
|
| 144 |
operation['operationId'] = self.get_operation_id(path, method) |
| 145 |
operation['description'] = self.get_description(path, method) |
| 146 |
|
| 147 |
parameters = [] |
| 148 |
parameters += self.get_path_parameters(path, method) |
| 149 |
parameters += self.get_pagination_parameters(path, method) |
| 150 |
parameters += self.get_filter_parameters(path, method) |
| 151 |
operation['parameters'] = parameters |
| 152 |
|
| 153 |
request_body = self.get_request_body(path, method) |
| 154 |
if request_body: |
| 155 |
operation['requestBody'] = request_body |
| 156 |
operation['responses'] = self.get_responses(path, method) |
| 157 |
operation['tags'] = self.get_tags(path, method) |
| 158 |
|
| 159 |
return operation |
| 160 |
|
| 161 |
def get_component_name(self, serializer): |
| 162 |
""" |
| 163 |
Compute the component's name from the serializer. |
| 164 |
Raise an exception if the serializer's class name is "Serializer" (case-insensitive). |
| 165 |
""" |
| 166 |
if self.component_name is not None: |
| 167 |
return self.component_name |
| 168 |
|
| 169 |
# use the serializer's class name as the component name. |
| 170 |
component_name = serializer.__class__.__name__ |
| 171 |
# We remove the "serializer" string from the class name. |
| 172 |
pattern = re.compile("serializer", re.IGNORECASE) |
| 173 |
component_name = pattern.sub("", component_name) |
| 174 |
|
| 175 |
if component_name == "": |
| 176 |
raise Exception( |
| 177 |
'"{}" is an invalid class name for schema generation. ' |
| 178 |
'Serializer\'s class name should be unique and explicit. e.g. "ItemSerializer"' |
| 179 |
.format(serializer.__class__.__name__) |
| 180 |
) |
| 181 |
|
| 182 |
return component_name |
| 183 |
|
| 184 |
def get_components(self, path, method): |
| 185 |
""" |
| 186 |
Return components with their properties from the serializer. |
| 187 |
""" |
| 188 |
|
| 189 |
if method.lower() == 'delete': |
| 190 |
return {} |
| 191 |
|
| 192 |
request_serializer = self.get_request_serializer(path, method) |
| 193 |
response_serializer = self.get_response_serializer(path, method) |
| 194 |
|
| 195 |
components = {} |
| 196 |
|
| 197 |
if isinstance(request_serializer, serializers.Serializer): |
| 198 |
component_name = self.get_component_name(request_serializer) |
| 199 |
content = self.map_serializer(request_serializer) |
| 200 |
components.setdefault(component_name, content) |
| 201 |
|
| 202 |
if isinstance(response_serializer, serializers.Serializer): |
| 203 |
component_name = self.get_component_name(response_serializer) |
| 204 |
content = self.map_serializer(response_serializer) |
| 205 |
components.setdefault(component_name, content) |
| 206 |
|
| 207 |
return components |
| 208 |
|
| 209 |
def _to_camel_case(self, snake_str): |
| 210 |
components = snake_str.split('_') |
| 211 |
# We capitalize the first letter of each component except the first one |
| 212 |
# with the 'title' method and join them together. |
| 213 |
return components[0] + ''.join(x.title() for x in components[1:]) |
| 214 |
|
| 215 |
def get_operation_id_base(self, path, method, action): |
| 216 |
""" |
| 217 |
Compute the base part for operation ID from the model, serializer or view name. |
| 218 |
""" |
| 219 |
model = getattr(getattr(self.view, 'queryset', None), 'model', None) |
| 220 |
|
| 221 |
if self.operation_id_base is not None: |
| 222 |
name = self.operation_id_base |
| 223 |
|
| 224 |
# Try to deduce the ID from the view's model |
| 225 |
elif model is not None: |
| 226 |
name = model.__name__ |
| 227 |
|
| 228 |
# Try with the serializer class name |
| 229 |
elif self.get_serializer(path, method) is not None: |
| 230 |
name = self.get_serializer(path, method).__class__.__name__ |
| 231 |
if name.endswith('Serializer'): |
| 232 |
name = name[:-10] |
| 233 |
|
| 234 |
# Fallback to the view name |
| 235 |
else: |
| 236 |
name = self.view.__class__.__name__ |
| 237 |
if name.endswith('APIView'): |
| 238 |
name = name[:-7] |
| 239 |
elif name.endswith('View'): |
| 240 |
name = name[:-4] |
| 241 |
|
| 242 |
# Due to camel-casing of classes and `action` being lowercase, apply title in order to find if action truly |
| 243 |
# comes at the end of the name |
| 244 |
if name.endswith(action.title()): # ListView, UpdateAPIView, ThingDelete ... |
| 245 |
name = name[:-len(action)] |
| 246 |
|
| 247 |
if action == 'list': |
| 248 |
assert inflection, '`inflection` must be installed for OpenAPI schema support.' |
| 249 |
name = inflection.pluralize(name) |
| 250 |
|
| 251 |
return name |
| 252 |
|
| 253 |
def get_operation_id(self, path, method): |
| 254 |
""" |
| 255 |
Compute an operation ID from the view type and get_operation_id_base method. |
| 256 |
""" |
| 257 |
method_name = getattr(self.view, 'action', method.lower()) |
| 258 |
if is_list_view(path, method, self.view): |
| 259 |
action = 'list' |
| 260 |
elif method_name not in self.method_mapping: |
| 261 |
action = self._to_camel_case(method_name) |
| 262 |
else: |
| 263 |
action = self.method_mapping[method.lower()] |
| 264 |
|
| 265 |
name = self.get_operation_id_base(path, method, action) |
| 266 |
|
| 267 |
return action + name |
| 268 |
|
| 269 |
def get_path_parameters(self, path, method): |
| 270 |
""" |
| 271 |
Return a list of parameters from templated path variables. |
| 272 |
""" |
| 273 |
assert uritemplate, '`uritemplate` must be installed for OpenAPI schema support.' |
| 274 |
|
| 275 |
model = getattr(getattr(self.view, 'queryset', None), 'model', None) |
| 276 |
parameters = [] |
| 277 |
|
| 278 |
for variable in uritemplate.variables(path): |
| 279 |
description = '' |
| 280 |
if model is not None: # TODO: test this. |
| 281 |
# Attempt to infer a field description if possible. |
| 282 |
try: |
| 283 |
model_field = model._meta.get_field(variable) |
| 284 |
except Exception: |
| 285 |
model_field = None |
| 286 |
|
| 287 |
if model_field is not None and model_field.help_text: |
| 288 |
description = force_str(model_field.help_text) |
| 289 |
elif model_field is not None and model_field.primary_key: |
| 290 |
description = get_pk_description(model, model_field) |
| 291 |
|
| 292 |
parameter = { |
| 293 |
"name": variable, |
| 294 |
"in": "path", |
| 295 |
"required": True, |
| 296 |
"description": description, |
| 297 |
'schema': { |
| 298 |
'type': 'string', # TODO: integer, pattern, ... |
| 299 |
}, |
| 300 |
} |
| 301 |
parameters.append(parameter) |
| 302 |
|
| 303 |
return parameters |
| 304 |
|
| 305 |
def get_filter_parameters(self, path, method): |
| 306 |
if not self.allows_filters(path, method): |
| 307 |
return [] |
| 308 |
parameters = [] |
| 309 |
for filter_backend in self.view.filter_backends: |
| 310 |
parameters += filter_backend().get_schema_operation_parameters(self.view) |
| 311 |
return parameters |
| 312 |
|
| 313 |
def allows_filters(self, path, method): |
| 314 |
""" |
| 315 |
Determine whether to include filter Fields in schema. |
| 316 |
|
| 317 |
Default implementation looks for ModelViewSet or GenericAPIView |
| 318 |
actions/methods that cause filtering on the default implementation. |
| 319 |
""" |
| 320 |
if getattr(self.view, 'filter_backends', None) is None: |
| 321 |
return False |
| 322 |
if hasattr(self.view, 'action'): |
| 323 |
return self.view.action in ["list", "retrieve", "update", "partial_update", "destroy"] |
| 324 |
return method.lower() in ["get", "put", "patch", "delete"] |
| 325 |
|
| 326 |
def get_pagination_parameters(self, path, method): |
| 327 |
view = self.view |
| 328 |
|
| 329 |
if not is_list_view(path, method, view): |
| 330 |
return [] |
| 331 |
|
| 332 |
paginator = self.get_paginator() |
| 333 |
if not paginator: |
| 334 |
return [] |
| 335 |
|
| 336 |
return paginator.get_schema_operation_parameters(view) |
| 337 |
|
| 338 |
def map_choicefield(self, field): |
| 339 |
choices = list(dict.fromkeys(field.choices)) # preserve order and remove duplicates |
| 340 |
if all(isinstance(choice, bool) for choice in choices): |
| 341 |
type = 'boolean' |
| 342 |
elif all(isinstance(choice, int) for choice in choices): |
| 343 |
type = 'integer' |
| 344 |
elif all(isinstance(choice, (int, float, Decimal)) for choice in choices): # `number` includes `integer` |
| 345 |
# Ref: https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.21 |
| 346 |
type = 'number' |
| 347 |
elif all(isinstance(choice, str) for choice in choices): |
| 348 |
type = 'string' |
| 349 |
else: |
| 350 |
type = None |
| 351 |
|
| 352 |
mapping = { |
| 353 |
# The value of `enum` keyword MUST be an array and SHOULD be unique. |
| 354 |
# Ref: https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.20 |
| 355 |
'enum': choices |
| 356 |
} |
| 357 |
|
| 358 |
# If We figured out `type` then and only then we should set it. It must be a string. |
| 359 |
# Ref: https://swagger.io/docs/specification/data-models/data-types/#mixed-type |
| 360 |
# It is optional but it can not be null. |
| 361 |
# Ref: https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.21 |
| 362 |
if type: |
| 363 |
mapping['type'] = type |
| 364 |
return mapping |
| 365 |
|
| 366 |
def map_field(self, field): |
| 367 |
|
| 368 |
# Nested Serializers, `many` or not. |
| 369 |
if isinstance(field, serializers.ListSerializer): |
| 370 |
return { |
| 371 |
'type': 'array', |
| 372 |
'items': self.map_serializer(field.child) |
| 373 |
} |
| 374 |
if isinstance(field, serializers.Serializer): |
| 375 |
data = self.map_serializer(field) |
| 376 |
data['type'] = 'object' |
| 377 |
return data |
| 378 |
|
| 379 |
# Related fields. |
| 380 |
if isinstance(field, serializers.ManyRelatedField): |
| 381 |
return { |
| 382 |
'type': 'array', |
| 383 |
'items': self.map_field(field.child_relation) |
| 384 |
} |
| 385 |
if isinstance(field, serializers.PrimaryKeyRelatedField): |
| 386 |
if getattr(field, "pk_field", False): |
| 387 |
return self.map_field(field=field.pk_field) |
| 388 |
model = getattr(field.queryset, 'model', None) |
| 389 |
if model is not None: |
| 390 |
model_field = model._meta.pk |
| 391 |
if isinstance(model_field, models.AutoField): |
| 392 |
return {'type': 'integer'} |
| 393 |
|
| 394 |
# ChoiceFields (single and multiple). |
| 395 |
# Q: |
| 396 |
# - Is 'type' required? |
| 397 |
# - can we determine the TYPE of a choicefield? |
| 398 |
if isinstance(field, serializers.MultipleChoiceField): |
| 399 |
return { |
| 400 |
'type': 'array', |
| 401 |
'items': self.map_choicefield(field) |
| 402 |
} |
| 403 |
|
| 404 |
if isinstance(field, serializers.ChoiceField): |
| 405 |
return self.map_choicefield(field) |
| 406 |
|
| 407 |
# ListField. |
| 408 |
if isinstance(field, serializers.ListField): |
| 409 |
mapping = { |
| 410 |
'type': 'array', |
| 411 |
'items': {}, |
| 412 |
} |
| 413 |
if not isinstance(field.child, _UnvalidatedField): |
| 414 |
mapping['items'] = self.map_field(field.child) |
| 415 |
return mapping |
| 416 |
|
| 417 |
# DateField and DateTimeField type is string |
| 418 |
if isinstance(field, serializers.DateField): |
| 419 |
return { |
| 420 |
'type': 'string', |
| 421 |
'format': 'date', |
| 422 |
} |
| 423 |
|
| 424 |
if isinstance(field, serializers.DateTimeField): |
| 425 |
return { |
| 426 |
'type': 'string', |
| 427 |
'format': 'date-time', |
| 428 |
} |
| 429 |
|
| 430 |
# "Formats such as "email", "uuid", and so on, MAY be used even though undefined by this specification." |
| 431 |
# see: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.2.md#data-types |
| 432 |
# see also: https://swagger.io/docs/specification/data-models/data-types/#string |
| 433 |
if isinstance(field, serializers.EmailField): |
| 434 |
return { |
| 435 |
'type': 'string', |
| 436 |
'format': 'email' |
| 437 |
} |
| 438 |
|
| 439 |
if isinstance(field, serializers.URLField): |
| 440 |
return { |
| 441 |
'type': 'string', |
| 442 |
'format': 'uri' |
| 443 |
} |
| 444 |
|
| 445 |
if isinstance(field, serializers.UUIDField): |
| 446 |
return { |
| 447 |
'type': 'string', |
| 448 |
'format': 'uuid' |
| 449 |
} |
| 450 |
|
| 451 |
if isinstance(field, serializers.IPAddressField): |
| 452 |
content = { |
| 453 |
'type': 'string', |
| 454 |
} |
| 455 |
if field.protocol != 'both': |
| 456 |
content['format'] = field.protocol |
| 457 |
return content |
| 458 |
|
| 459 |
if isinstance(field, serializers.DecimalField): |
| 460 |
if getattr(field, 'coerce_to_string', api_settings.COERCE_DECIMAL_TO_STRING): |
| 461 |
content = { |
| 462 |
'type': 'string', |
| 463 |
'format': 'decimal', |
| 464 |
} |
| 465 |
else: |
| 466 |
content = { |
| 467 |
'type': 'number' |
| 468 |
} |
| 469 |
|
| 470 |
if field.decimal_places: |
| 471 |
content['multipleOf'] = float('.' + (field.decimal_places - 1) * '0' + '1') |
| 472 |
if field.max_whole_digits: |
| 473 |
content['maximum'] = int(field.max_whole_digits * '9') + 1 |
| 474 |
content['minimum'] = -content['maximum'] |
| 475 |
self._map_min_max(field, content) |
| 476 |
return content |
| 477 |
|
| 478 |
if isinstance(field, serializers.FloatField): |
| 479 |
content = { |
| 480 |
'type': 'number', |
| 481 |
} |
| 482 |
self._map_min_max(field, content) |
| 483 |
return content |
| 484 |
|
| 485 |
if isinstance(field, serializers.IntegerField): |
| 486 |
content = { |
| 487 |
'type': 'integer' |
| 488 |
} |
| 489 |
self._map_min_max(field, content) |
| 490 |
# Use int64 format when the value range exceeds signed int32 bounds. |
| 491 |
maximum = content.get('maximum') |
| 492 |
minimum = content.get('minimum') |
| 493 |
if ( |
| 494 |
(maximum is not None and ( |
| 495 |
int(maximum) > 2147483647 or int(maximum) < -2147483648 |
| 496 |
)) or |
| 497 |
(minimum is not None and ( |
| 498 |
int(minimum) > 2147483647 or int(minimum) < -2147483648 |
| 499 |
)) |
| 500 |
): |
| 501 |
content['format'] = 'int64' |
| 502 |
return content |
| 503 |
|
| 504 |
if isinstance(field, serializers.FileField): |
| 505 |
return { |
| 506 |
'type': 'string', |
| 507 |
'format': 'binary' |
| 508 |
} |
| 509 |
|
| 510 |
# Simplest cases, default to 'string' type: |
| 511 |
FIELD_CLASS_SCHEMA_TYPE = { |
| 512 |
serializers.BooleanField: 'boolean', |
| 513 |
serializers.JSONField: 'object', |
| 514 |
serializers.DictField: 'object', |
| 515 |
serializers.HStoreField: 'object', |
| 516 |
} |
| 517 |
return {'type': FIELD_CLASS_SCHEMA_TYPE.get(field.__class__, 'string')} |
| 518 |
|
| 519 |
def _map_min_max(self, field, content): |
| 520 |
if field.max_value is not None: |
| 521 |
content['maximum'] = field.max_value |
| 522 |
if field.min_value is not None: |
| 523 |
content['minimum'] = field.min_value |
| 524 |
|
| 525 |
def map_serializer(self, serializer): |
| 526 |
# Assuming we have a valid serializer instance. |
| 527 |
required = [] |
| 528 |
properties = {} |
| 529 |
|
| 530 |
for field in serializer.fields.values(): |
| 531 |
if isinstance(field, serializers.HiddenField): |
| 532 |
continue |
| 533 |
|
| 534 |
if field.required and not serializer.partial: |
| 535 |
required.append(self.get_field_name(field)) |
| 536 |
|
| 537 |
schema = self.map_field(field) |
| 538 |
if field.read_only: |
| 539 |
schema['readOnly'] = True |
| 540 |
if field.write_only: |
| 541 |
schema['writeOnly'] = True |
| 542 |
if field.allow_null: |
| 543 |
schema['nullable'] = True |
| 544 |
if field.default is not None and field.default != empty and not callable(field.default): |
| 545 |
schema['default'] = field.default |
| 546 |
if field.help_text: |
| 547 |
schema['description'] = str(field.help_text) |
| 548 |
self.map_field_validators(field, schema) |
| 549 |
|
| 550 |
properties[self.get_field_name(field)] = schema |
| 551 |
|
| 552 |
result = { |
| 553 |
'type': 'object', |
| 554 |
'properties': properties |
| 555 |
} |
| 556 |
if required: |
| 557 |
result['required'] = required |
| 558 |
|
| 559 |
return result |
| 560 |
|
| 561 |
def map_field_validators(self, field, schema): |
| 562 |
""" |
| 563 |
map field validators |
| 564 |
""" |
| 565 |
for v in field.validators: |
| 566 |
# "Formats such as "email", "uuid", and so on, MAY be used even though undefined by this specification." |
| 567 |
# https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.2.md#data-types |
| 568 |
if isinstance(v, EmailValidator): |
| 569 |
schema['format'] = 'email' |
| 570 |
if isinstance(v, URLValidator): |
| 571 |
schema['format'] = 'uri' |
| 572 |
if isinstance(v, RegexValidator): |
| 573 |
# In Python, the token \Z does what \z does in other engines. |
| 574 |
# https://stackoverflow.com/questions/53283160 |
| 575 |
schema['pattern'] = v.regex.pattern.replace('\\Z', '\\z') |
| 576 |
elif isinstance(v, MaxLengthValidator): |
| 577 |
attr_name = 'maxLength' |
| 578 |
if isinstance(field, serializers.ListField): |
| 579 |
attr_name = 'maxItems' |
| 580 |
schema[attr_name] = v.limit_value |
| 581 |
elif isinstance(v, MinLengthValidator): |
| 582 |
attr_name = 'minLength' |
| 583 |
if isinstance(field, serializers.ListField): |
| 584 |
attr_name = 'minItems' |
| 585 |
schema[attr_name] = v.limit_value |
| 586 |
elif isinstance(v, MaxValueValidator): |
| 587 |
schema['maximum'] = v.limit_value |
| 588 |
elif isinstance(v, MinValueValidator): |
| 589 |
schema['minimum'] = v.limit_value |
| 590 |
elif isinstance(v, DecimalValidator) and \ |
| 591 |
not getattr(field, 'coerce_to_string', api_settings.COERCE_DECIMAL_TO_STRING): |
| 592 |
if v.decimal_places: |
| 593 |
schema['multipleOf'] = float('.' + (v.decimal_places - 1) * '0' + '1') |
| 594 |
if v.max_digits: |
| 595 |
digits = v.max_digits |
| 596 |
if v.decimal_places is not None and v.decimal_places > 0: |
| 597 |
digits -= v.decimal_places |
| 598 |
schema['maximum'] = int(digits * '9') + 1 |
| 599 |
schema['minimum'] = -schema['maximum'] |
| 600 |
|
| 601 |
def get_field_name(self, field): |
| 602 |
""" |
| 603 |
Override this method if you want to change schema field name. |
| 604 |
For example, convert snake_case field name to camelCase. |
| 605 |
""" |
| 606 |
return field.field_name |
| 607 |
|
| 608 |
def get_paginator(self): |
| 609 |
pagination_class = getattr(self.view, 'pagination_class', None) |
| 610 |
if pagination_class: |
| 611 |
return pagination_class() |
| 612 |
return None |
| 613 |
|
| 614 |
def map_parsers(self, path, method): |
| 615 |
return list(map(attrgetter('media_type'), self.view.parser_classes)) |
| 616 |
|
| 617 |
def map_renderers(self, path, method): |
| 618 |
media_types = [] |
| 619 |
for renderer in self.view.renderer_classes: |
| 620 |
# BrowsableAPIRenderer not relevant to OpenAPI spec |
| 621 |
if issubclass(renderer, renderers.BrowsableAPIRenderer): |
| 622 |
continue |
| 623 |
media_types.append(renderer.media_type) |
| 624 |
return media_types |
| 625 |
|
| 626 |
def get_serializer(self, path, method): |
| 627 |
view = self.view |
| 628 |
|
| 629 |
if not hasattr(view, 'get_serializer'): |
| 630 |
return None |
| 631 |
|
| 632 |
try: |
| 633 |
return view.get_serializer() |
| 634 |
except exceptions.APIException: |
| 635 |
warnings.warn('{}.get_serializer() raised an exception during ' |
| 636 |
'schema generation. Serializer fields will not be ' |
| 637 |
'generated for {} {}.' |
| 638 |
.format(view.__class__.__name__, method, path)) |
| 639 |
return None |
| 640 |
|
| 641 |
def get_request_serializer(self, path, method): |
| 642 |
""" |
| 643 |
Override this method if your view uses a different serializer for |
| 644 |
handling request body. |
| 645 |
""" |
| 646 |
return self.get_serializer(path, method) |
| 647 |
|
| 648 |
def get_response_serializer(self, path, method): |
| 649 |
""" |
| 650 |
Override this method if your view uses a different serializer for |
| 651 |
populating response data. |
| 652 |
""" |
| 653 |
return self.get_serializer(path, method) |
| 654 |
|
| 655 |
def get_reference(self, serializer): |
| 656 |
return {'$ref': f'#/components/schemas/{self.get_component_name(serializer)}'} |
| 657 |
|
| 658 |
def get_request_body(self, path, method): |
| 659 |
if method not in ('PUT', 'PATCH', 'POST'): |
| 660 |
return {} |
| 661 |
|
| 662 |
self.request_media_types = self.map_parsers(path, method) |
| 663 |
|
| 664 |
serializer = self.get_request_serializer(path, method) |
| 665 |
|
| 666 |
if not isinstance(serializer, serializers.Serializer): |
| 667 |
item_schema = {} |
| 668 |
else: |
| 669 |
item_schema = self.get_reference(serializer) |
| 670 |
|
| 671 |
return { |
| 672 |
'content': { |
| 673 |
ct: {'schema': item_schema} |
| 674 |
for ct in self.request_media_types |
| 675 |
} |
| 676 |
} |
| 677 |
|
| 678 |
def get_responses(self, path, method): |
| 679 |
if method == 'DELETE': |
| 680 |
return { |
| 681 |
'204': { |
| 682 |
'description': '' |
| 683 |
} |
| 684 |
} |
| 685 |
|
| 686 |
self.response_media_types = self.map_renderers(path, method) |
| 687 |
|
| 688 |
serializer = self.get_response_serializer(path, method) |
| 689 |
|
| 690 |
if not isinstance(serializer, serializers.Serializer): |
| 691 |
item_schema = {} |
| 692 |
else: |
| 693 |
item_schema = self.get_reference(serializer) |
| 694 |
|
| 695 |
if is_list_view(path, method, self.view): |
| 696 |
response_schema = { |
| 697 |
'type': 'array', |
| 698 |
'items': item_schema, |
| 699 |
} |
| 700 |
paginator = self.get_paginator() |
| 701 |
if paginator: |
| 702 |
response_schema = paginator.get_paginated_response_schema(response_schema) |
| 703 |
else: |
| 704 |
response_schema = item_schema |
| 705 |
status_code = '201' if method == 'POST' else '200' |
| 706 |
return { |
| 707 |
status_code: { |
| 708 |
'content': { |
| 709 |
ct: {'schema': response_schema} |
| 710 |
for ct in self.response_media_types |
| 711 |
}, |
| 712 |
# description is a mandatory property, |
| 713 |
# https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#responseObject |
| 714 |
# TODO: put something meaningful into it |
| 715 |
'description': "" |
| 716 |
} |
| 717 |
} |
| 718 |
|
| 719 |
def get_tags(self, path, method): |
| 720 |
# If user have specified tags, use them. |
| 721 |
if self._tags: |
| 722 |
return self._tags |
| 723 |
|
| 724 |
# First element of a specific path could be valid tag. This is a fallback solution. |
| 725 |
# PUT, PATCH, GET(Retrieve), DELETE: /user_profile/{id}/ tags = [user-profile] |
| 726 |
# POST, GET(List): /user_profile/ tags = [user-profile] |
| 727 |
if path.startswith('/'): |
| 728 |
path = path[1:] |
| 729 |
|
| 730 |
return [path.split('/')[0].replace('_', '-')] |