| 1 |
import logging |
| 2 |
|
| 3 |
from rest_framework.request import is_form_media_type |
| 4 |
from rest_framework.schemas import AutoSchema |
| 5 |
from rest_framework.status import is_success |
| 6 |
|
| 7 |
from .. import openapi |
| 8 |
from ..errors import SwaggerGenerationError |
| 9 |
from ..utils import ( |
| 10 |
filter_none, |
| 11 |
force_real_str, |
| 12 |
force_serializer_instance, |
| 13 |
get_consumes, |
| 14 |
get_produces, |
| 15 |
guess_response_status, |
| 16 |
merge_params, |
| 17 |
no_body, |
| 18 |
param_list_to_dict, |
| 19 |
) |
| 20 |
from .base import ViewInspector, call_view_method |
| 21 |
|
| 22 |
logger = logging.getLogger(__name__) |
| 23 |
|
| 24 |
|
| 25 |
class SwaggerAutoSchema(ViewInspector): |
| 26 |
def __init__( |
| 27 |
self, view, path, method, components, request, overrides, operation_keys=None |
| 28 |
): |
| 29 |
super(SwaggerAutoSchema, self).__init__( |
| 30 |
view, path, method, components, request, overrides |
| 31 |
) |
| 32 |
self._sch = AutoSchema() |
| 33 |
self._sch.view = view |
| 34 |
self.operation_keys = operation_keys |
| 35 |
|
| 36 |
def get_operation(self, operation_keys=None): |
| 37 |
operation_keys = operation_keys or self.operation_keys |
| 38 |
|
| 39 |
consumes = self.get_consumes() |
| 40 |
produces = self.get_produces() |
| 41 |
|
| 42 |
body = self.get_request_body_parameters(consumes) |
| 43 |
query = self.get_query_parameters() |
| 44 |
parameters = body + query |
| 45 |
parameters = filter_none(parameters) |
| 46 |
parameters = self.add_manual_parameters(parameters) |
| 47 |
|
| 48 |
operation_id = self.get_operation_id(operation_keys) |
| 49 |
summary, description = self.get_summary_and_description() |
| 50 |
security = self.get_security() |
| 51 |
assert security is None or isinstance(security, list), ( |
| 52 |
"security must be a list of security requirement objects" |
| 53 |
) |
| 54 |
deprecated = self.is_deprecated() |
| 55 |
tags = self.get_tags(operation_keys) |
| 56 |
|
| 57 |
responses = self.get_responses() |
| 58 |
|
| 59 |
return openapi.Operation( |
| 60 |
operation_id=operation_id, |
| 61 |
description=force_real_str(description), |
| 62 |
summary=force_real_str(summary), |
| 63 |
responses=responses, |
| 64 |
parameters=parameters, |
| 65 |
consumes=consumes, |
| 66 |
produces=produces, |
| 67 |
tags=tags, |
| 68 |
security=security, |
| 69 |
deprecated=deprecated, |
| 70 |
) |
| 71 |
|
| 72 |
def get_request_body_parameters(self, consumes): |
| 73 |
"""Return the request body parameters for this view. |br| |
| 74 |
This is either: |
| 75 |
|
| 76 |
- a list with a single object Parameter with a :class:`.Schema` derived from |
| 77 |
the request serializer |
| 78 |
- a list of primitive Parameters parsed as form data |
| 79 |
|
| 80 |
:param list[str] consumes: a list of accepted MIME types as returned by |
| 81 |
:meth:`.get_consumes` |
| 82 |
:return: a (potentially empty) list of :class:`.Parameter`\\ s either |
| 83 |
``in: body`` or ``in: formData`` |
| 84 |
:rtype: list[openapi.Parameter] |
| 85 |
""" |
| 86 |
serializer = self.get_request_serializer() |
| 87 |
schema = None |
| 88 |
if serializer is None: |
| 89 |
return [] |
| 90 |
|
| 91 |
if isinstance(serializer, openapi.Schema.OR_REF): |
| 92 |
schema = serializer |
| 93 |
|
| 94 |
if any(is_form_media_type(encoding) for encoding in consumes): |
| 95 |
if schema is not None: |
| 96 |
raise SwaggerGenerationError("form request body cannot be a Schema") |
| 97 |
return self.get_request_form_parameters(serializer) |
| 98 |
else: |
| 99 |
if schema is None: |
| 100 |
schema = self.get_request_body_schema(serializer) |
| 101 |
return [self.make_body_parameter(schema)] if schema is not None else [] |
| 102 |
|
| 103 |
def get_view_serializer(self): |
| 104 |
"""Return the serializer as defined by the view's ``get_serializer()`` method. |
| 105 |
|
| 106 |
:return: the view's ``Serializer`` |
| 107 |
:rtype: rest_framework.serializers.Serializer |
| 108 |
""" |
| 109 |
return call_view_method(self.view, "get_serializer") |
| 110 |
|
| 111 |
def _get_request_body_override(self): |
| 112 |
"""Parse the request_body key in the override dict. This method is not public |
| 113 |
API.""" |
| 114 |
body_override = self.overrides.get("request_body", None) |
| 115 |
|
| 116 |
if body_override is not None: |
| 117 |
if body_override is no_body: |
| 118 |
return no_body |
| 119 |
if self.method not in self.body_methods: |
| 120 |
raise SwaggerGenerationError( |
| 121 |
"request_body can only be applied to (" |
| 122 |
+ ",".join(self.body_methods) |
| 123 |
+ "); are you looking for query_serializer or manual_parameters?" |
| 124 |
) |
| 125 |
if isinstance(body_override, openapi.Schema.OR_REF): |
| 126 |
return body_override |
| 127 |
return force_serializer_instance(body_override) |
| 128 |
|
| 129 |
return body_override |
| 130 |
|
| 131 |
def get_request_serializer(self): |
| 132 |
"""Return the request serializer (used for parsing the request payload) for this |
| 133 |
endpoint. |
| 134 |
|
| 135 |
:return: the request serializer, or one of :class:`.Schema`, |
| 136 |
:class:`.SchemaRef`, ``None`` |
| 137 |
:rtype: rest_framework.serializers.Serializer |
| 138 |
""" |
| 139 |
body_override = self._get_request_body_override() |
| 140 |
|
| 141 |
if body_override is None and self.method in self.implicit_body_methods: |
| 142 |
return self.get_view_serializer() |
| 143 |
|
| 144 |
if body_override is no_body: |
| 145 |
return None |
| 146 |
|
| 147 |
return body_override |
| 148 |
|
| 149 |
def get_request_form_parameters(self, serializer): |
| 150 |
"""Given a Serializer, return a list of ``in: formData`` |
| 151 |
:class:`.Parameter`\\ s. |
| 152 |
|
| 153 |
:param serializer: the view's request serializer as returned by |
| 154 |
:meth:`.get_request_serializer` |
| 155 |
:rtype: list[openapi.Parameter] |
| 156 |
""" |
| 157 |
return self.serializer_to_parameters(serializer, in_=openapi.IN_FORM) |
| 158 |
|
| 159 |
def get_request_body_schema(self, serializer): |
| 160 |
"""Return the :class:`.Schema` for a given request's body data. Only applies to |
| 161 |
PUT, PATCH and POST requests. |
| 162 |
|
| 163 |
:param serializer: the view's request serializer as returned by |
| 164 |
:meth:`.get_request_serializer` |
| 165 |
:rtype: openapi.Schema |
| 166 |
""" |
| 167 |
return self.serializer_to_schema(serializer) |
| 168 |
|
| 169 |
def make_body_parameter(self, schema): |
| 170 |
"""Given a :class:`.Schema` object, create an ``in: body`` :class:`.Parameter`. |
| 171 |
|
| 172 |
:param openapi.Schema schema: the request body schema |
| 173 |
:rtype: openapi.Parameter |
| 174 |
""" |
| 175 |
return openapi.Parameter( |
| 176 |
name="data", in_=openapi.IN_BODY, required=True, schema=schema |
| 177 |
) |
| 178 |
|
| 179 |
def add_manual_parameters(self, parameters): |
| 180 |
"""Add/replace parameters from the given list of automatically generated request |
| 181 |
parameters. |
| 182 |
|
| 183 |
:param list[openapi.Parameter] parameters: generated parameters |
| 184 |
:return: modified parameters |
| 185 |
:rtype: list[openapi.Parameter] |
| 186 |
""" |
| 187 |
manual_parameters = self.overrides.get("manual_parameters", None) or [] |
| 188 |
|
| 189 |
if any( |
| 190 |
param.in_ == openapi.IN_BODY for param in manual_parameters |
| 191 |
): |
| 192 |
raise SwaggerGenerationError( |
| 193 |
"specify the body parameter as a Schema or Serializer in request_body" |
| 194 |
) |
| 195 |
if any( |
| 196 |
param.in_ == openapi.IN_FORM for param in manual_parameters |
| 197 |
): |
| 198 |
has_body_parameter = any( |
| 199 |
param.in_ == openapi.IN_BODY for param in parameters |
| 200 |
) |
| 201 |
if has_body_parameter or not any( |
| 202 |
is_form_media_type(encoding) for encoding in self.get_consumes() |
| 203 |
): |
| 204 |
raise SwaggerGenerationError( |
| 205 |
"cannot add form parameters when the request has a request body; " |
| 206 |
"did you forget to set an appropriate parser class on the view?" |
| 207 |
) |
| 208 |
if self.method not in self.body_methods: |
| 209 |
raise SwaggerGenerationError( |
| 210 |
"form parameters can only be applied to " |
| 211 |
"(" + ",".join(self.body_methods) + ") HTTP methods" |
| 212 |
) |
| 213 |
|
| 214 |
return merge_params(parameters, manual_parameters) |
| 215 |
|
| 216 |
def get_responses(self): |
| 217 |
"""Get the possible responses for this view as a swagger :class:`.Responses` |
| 218 |
object. |
| 219 |
|
| 220 |
:return: the documented responses |
| 221 |
:rtype: openapi.Responses |
| 222 |
""" |
| 223 |
response_serializers = self.get_response_serializers() |
| 224 |
return openapi.Responses( |
| 225 |
responses=self.get_response_schemas(response_serializers) |
| 226 |
) |
| 227 |
|
| 228 |
def get_default_response_serializer(self): |
| 229 |
"""Return the default response serializer for this endpoint. This is derived |
| 230 |
from either the ``request_body`` override or the request serializer |
| 231 |
(:meth:`.get_view_serializer`). |
| 232 |
|
| 233 |
:return: response serializer, :class:`.Schema`, :class:`.SchemaRef`, ``None`` |
| 234 |
""" |
| 235 |
body_override = self._get_request_body_override() |
| 236 |
if body_override and body_override is not no_body: |
| 237 |
return body_override |
| 238 |
|
| 239 |
return self.get_view_serializer() |
| 240 |
|
| 241 |
def get_default_responses(self): |
| 242 |
"""Get the default responses determined for this view from the request |
| 243 |
serializer and request method. |
| 244 |
|
| 245 |
:type: dict[str, openapi.Schema] |
| 246 |
""" |
| 247 |
method = self.method.lower() |
| 248 |
|
| 249 |
default_status = guess_response_status(method) |
| 250 |
default_schema = "" |
| 251 |
if method in ("get", "post", "put", "patch"): |
| 252 |
default_schema = self.get_default_response_serializer() |
| 253 |
|
| 254 |
default_schema = default_schema or "" |
| 255 |
if default_schema and not isinstance(default_schema, openapi.Schema): |
| 256 |
default_schema = self.serializer_to_schema(default_schema) or "" |
| 257 |
|
| 258 |
if default_schema: |
| 259 |
if self.has_list_response(): |
| 260 |
default_schema = openapi.Schema( |
| 261 |
type=openapi.TYPE_ARRAY, items=default_schema |
| 262 |
) |
| 263 |
if self.should_page(): |
| 264 |
default_schema = ( |
| 265 |
self.get_paginated_response(default_schema) or default_schema |
| 266 |
) |
| 267 |
|
| 268 |
return {str(default_status): default_schema} |
| 269 |
|
| 270 |
def get_response_serializers(self): |
| 271 |
"""Return the response codes that this view is expected to return, and the |
| 272 |
serializer for each response body. The return value should be a dict where the |
| 273 |
keys are possible status codes, and values are either strings, |
| 274 |
``Serializer``\\ s, :class:`.Schema`, :class:`.SchemaRef` or :class:`.Response` |
| 275 |
objects. See |
| 276 |
:func:`@swagger_auto_schema <.swagger_auto_schema>` for more details. |
| 277 |
|
| 278 |
:return: the response serializers |
| 279 |
:rtype: dict |
| 280 |
""" |
| 281 |
manual_responses = self.overrides.get("responses", None) or {} |
| 282 |
manual_responses = {str(sc): resp for sc, resp in manual_responses.items()} |
| 283 |
|
| 284 |
responses = {} |
| 285 |
if not any(is_success(int(sc)) for sc in manual_responses if sc != "default"): |
| 286 |
responses = self.get_default_responses() |
| 287 |
|
| 288 |
responses.update((str(sc), resp) for sc, resp in manual_responses.items()) |
| 289 |
return responses |
| 290 |
|
| 291 |
def get_response_schemas(self, response_serializers): |
| 292 |
"""Return the :class:`.openapi.Response` objects calculated for this view. |
| 293 |
|
| 294 |
:param dict response_serializers: response serializers as returned by |
| 295 |
:meth:`.get_response_serializers` |
| 296 |
:return: a dictionary of status code to :class:`.Response` object |
| 297 |
:rtype: dict[str, openapi.Response] |
| 298 |
""" |
| 299 |
responses = {} |
| 300 |
for sc, serializer in response_serializers.items(): |
| 301 |
if isinstance(serializer, str): |
| 302 |
response = openapi.Response(description=force_real_str(serializer)) |
| 303 |
elif not serializer: |
| 304 |
continue |
| 305 |
elif isinstance(serializer, openapi.Response): |
| 306 |
response = serializer |
| 307 |
if hasattr(response, "schema") and not isinstance( |
| 308 |
response.schema, openapi.Schema.OR_REF |
| 309 |
): |
| 310 |
serializer = force_serializer_instance(response.schema) |
| 311 |
response.schema = self.serializer_to_schema(serializer) |
| 312 |
elif isinstance(serializer, openapi.Schema.OR_REF): |
| 313 |
response = openapi.Response( |
| 314 |
description="", |
| 315 |
schema=serializer, |
| 316 |
) |
| 317 |
elif isinstance(serializer, openapi._Ref): |
| 318 |
response = serializer |
| 319 |
else: |
| 320 |
serializer = force_serializer_instance(serializer) |
| 321 |
response = openapi.Response( |
| 322 |
description="", |
| 323 |
schema=self.serializer_to_schema(serializer), |
| 324 |
) |
| 325 |
|
| 326 |
responses[str(sc)] = response |
| 327 |
|
| 328 |
return responses |
| 329 |
|
| 330 |
def get_query_serializer(self): |
| 331 |
"""Return the query serializer (used for parsing query parameters) for this |
| 332 |
endpoint. |
| 333 |
|
| 334 |
:return: the query serializer, or ``None`` |
| 335 |
""" |
| 336 |
query_serializer = self.overrides.get("query_serializer", None) |
| 337 |
if query_serializer is not None: |
| 338 |
query_serializer = force_serializer_instance(query_serializer) |
| 339 |
return query_serializer |
| 340 |
|
| 341 |
def get_query_parameters(self): |
| 342 |
"""Return the query parameters accepted by this view. |
| 343 |
|
| 344 |
:rtype: list[openapi.Parameter] |
| 345 |
""" |
| 346 |
natural_parameters = ( |
| 347 |
self.get_filter_parameters() + self.get_pagination_parameters() |
| 348 |
) |
| 349 |
|
| 350 |
query_serializer = self.get_query_serializer() |
| 351 |
serializer_parameters = [] |
| 352 |
if query_serializer is not None: |
| 353 |
serializer_parameters = self.serializer_to_parameters( |
| 354 |
query_serializer, in_=openapi.IN_QUERY |
| 355 |
) |
| 356 |
|
| 357 |
if ( |
| 358 |
len( |
| 359 |
set(param_list_to_dict(natural_parameters)) |
| 360 |
& set(param_list_to_dict(serializer_parameters)) |
| 361 |
) |
| 362 |
!= 0 |
| 363 |
): |
| 364 |
raise SwaggerGenerationError( |
| 365 |
"your query_serializer contains fields that conflict with the " |
| 366 |
"filter_backend or paginator_class on the view - %s %s" |
| 367 |
% (self.method, self.path) |
| 368 |
) |
| 369 |
|
| 370 |
return natural_parameters + serializer_parameters |
| 371 |
|
| 372 |
def get_operation_id(self, operation_keys=None): |
| 373 |
"""Return an unique ID for this operation. The ID must be unique across |
| 374 |
all :class:`.Operation` objects in the API. |
| 375 |
|
| 376 |
:param tuple[str] operation_keys: an array of keys derived from the path |
| 377 |
describing the hierarchical layout of this view in the API; e.g. |
| 378 |
``('snippets', 'list')``, ``('snippets', 'retrieve')``, etc. |
| 379 |
:rtype: str |
| 380 |
""" |
| 381 |
operation_keys = operation_keys or self.operation_keys |
| 382 |
|
| 383 |
operation_id = self.overrides.get("operation_id", "") |
| 384 |
if not operation_id: |
| 385 |
operation_id = "_".join(operation_keys) |
| 386 |
return operation_id |
| 387 |
|
| 388 |
def split_summary_from_description(self, description): |
| 389 |
"""Decide if and how to split a summary out of the given description. The |
| 390 |
default implementation uses the first paragraph of the description as a summary |
| 391 |
if it is less than 120 characters long. |
| 392 |
|
| 393 |
:param description: the full description to be analyzed |
| 394 |
:return: summary and description |
| 395 |
:rtype: (str,str) |
| 396 |
""" |
| 397 |
|
| 398 |
summary = None |
| 399 |
summary_max_len = ( |
| 400 |
120 |
| 401 |
) |
| 402 |
sections = description.split("\n\n", 1) |
| 403 |
if len(sections) == 2: |
| 404 |
sections[0] = sections[0].strip() |
| 405 |
if len(sections[0]) < summary_max_len: |
| 406 |
summary, description = sections |
| 407 |
description = description.strip() |
| 408 |
|
| 409 |
return summary, description |
| 410 |
|
| 411 |
def get_summary_and_description(self): |
| 412 |
"""Return an operation summary and description determined from the view's |
| 413 |
docstring. |
| 414 |
|
| 415 |
:return: summary and description |
| 416 |
:rtype: (str,str) |
| 417 |
""" |
| 418 |
description = self.overrides.get("operation_description", None) |
| 419 |
summary = self.overrides.get("operation_summary", None) |
| 420 |
if description is None: |
| 421 |
description = self._sch.get_description(self.path, self.method) or "" |
| 422 |
description = description.strip().replace("\r", "") |
| 423 |
|
| 424 |
if description and (summary is None): |
| 425 |
|
| 426 |
summary, description = self.split_summary_from_description(description) |
| 427 |
|
| 428 |
return summary, description |
| 429 |
|
| 430 |
def get_security(self): |
| 431 |
"""Return a list of security requirements for this operation. |
| 432 |
|
| 433 |
Returning an empty list marks the endpoint as unauthenticated (i.e. removes all |
| 434 |
accepted authentication schemes). Returning ``None`` will inherit the top-level |
| 435 |
security requirements. |
| 436 |
|
| 437 |
:return: security requirements |
| 438 |
:rtype: list[dict[str,list[str]]]""" |
| 439 |
return self.overrides.get("security", None) |
| 440 |
|
| 441 |
def is_deprecated(self): |
| 442 |
"""Return ``True`` if this operation is to be marked as deprecated. |
| 443 |
|
| 444 |
:return: deprecation status |
| 445 |
:rtype: bool |
| 446 |
""" |
| 447 |
return self.overrides.get("deprecated", None) |
| 448 |
|
| 449 |
def get_tags(self, operation_keys=None): |
| 450 |
"""Get a list of tags for this operation. Tags determine how operations relate |
| 451 |
with each other, and in the UI each tag will show as a group containing the |
| 452 |
operations that use it. If not provided in overrides, tags will be inferred |
| 453 |
from the operation url. |
| 454 |
|
| 455 |
:param tuple[str] operation_keys: an array of keys derived from the path |
| 456 |
describing the hierarchical layout of this view in the API; e.g. |
| 457 |
``('snippets', 'list')``, ``('snippets', 'retrieve')``, etc. |
| 458 |
:rtype: list[str] |
| 459 |
""" |
| 460 |
operation_keys = operation_keys or self.operation_keys |
| 461 |
|
| 462 |
tags = self.overrides.get("tags") |
| 463 |
if not tags: |
| 464 |
tags = [operation_keys[0]] |
| 465 |
|
| 466 |
return tags |
| 467 |
|
| 468 |
def get_consumes(self): |
| 469 |
"""Return the MIME types this endpoint can consume. |
| 470 |
|
| 471 |
:rtype: list[str] |
| 472 |
""" |
| 473 |
return self.overrides.get("consumes") or get_consumes(self.get_parser_classes()) |
| 474 |
|
| 475 |
def get_produces(self): |
| 476 |
"""Return the MIME types this endpoint can produce. |
| 477 |
|
| 478 |
:rtype: list[str] |
| 479 |
""" |
| 480 |
return self.overrides.get("produces") or get_produces( |
| 481 |
self.get_renderer_classes() |
| 482 |
) |