Debian Codegraph @

src/drf_yasg/generators.py

raw symbols SCIP
1 import copy
2 import logging
3 import re
4 import urllib.parse as urlparse
5 from collections import defaultdict
6
7 import uritemplate
8 from django.urls import URLPattern, URLResolver
9 from rest_framework import versioning
10 from rest_framework.schemas.generators import EndpointEnumerator as _EndpointEnumerator
11 from rest_framework.schemas.generators import endpoint_ordering, get_pk_name
12 from rest_framework.schemas.openapi import SchemaGenerator
13 from rest_framework.schemas.utils import get_pk_description
14 from rest_framework.settings import api_settings
15
16 from . import openapi
17 from .app_settings import swagger_settings
18 from .errors import SwaggerGenerationError
19 from .inspectors.field import (
20 get_basic_type_info,
21 get_queryset_field,
22 get_queryset_from_view,
23 )
24 from .openapi import ReferenceResolver, SwaggerDict
25 from .utils import force_real_str, get_consumes, get_produces, is_list_view
26
27 logger = logging.getLogger(__name__)
28
29 PATH_PARAMETER_RE = re.compile(r"{(?P<parameter>\w+)}")
30
31
32 def common_path(paths):
33 split_paths = [path.strip("/").split("/") for path in paths]
34 s1 = min(split_paths)
35 s2 = max(split_paths)
36 common = s1
37 for i, c in enumerate(s1):
38 if c != s2[i]:
39 common = s1[:i]
40 break
41 return "/" + "/".join(common)
42
43
44 def is_custom_action(action):
45 return action not in {
46 "retrieve",
47 "list",
48 "create",
49 "update",
50 "partial_update",
51 "destroy",
52 }
53
54
55 class EndpointEnumerator(_EndpointEnumerator):
56 def __init__(self, patterns=None, urlconf=None, request=None):
57 super(EndpointEnumerator, self).__init__(patterns, urlconf)
58 self.request = request
59
60 def get_path_from_regex(self, path_regex):
61 if path_regex.endswith(")"):
62 logger.warning(
63 "url pattern does not end in $ ('%s') - unexpected things might happen",
64 path_regex,
65 )
66 return self.unescape_path(
67 super(EndpointEnumerator, self).get_path_from_regex(path_regex)
68 )
69
70 def should_include_endpoint(
71 self, path, callback, app_name="", namespace="", url_name=None
72 ):
73 if not super(EndpointEnumerator, self).should_include_endpoint(path, callback):
74 return False
75
76 version = getattr(self.request, "version", None)
77 versioning_class = getattr(callback.cls, "versioning_class", None)
78 if versioning_class is not None and issubclass(
79 versioning_class, versioning.NamespaceVersioning
80 ):
81 if version and version not in namespace.split(":"):
82 return False
83
84 if getattr(callback.cls, "swagger_schema", object()) is None:
85 return False
86
87 return True
88
89 def replace_version(self, path, callback):
90 """If ``request.version`` is not ``None`` and `callback` uses
91 ``URLPathVersioning``, this function replaces the ``version`` parameter in
92 `path` with the actual version.
93
94 :param str path: the templated path
95 :param callback: the view callback
96 :rtype: str
97 """
98 versioning_class = getattr(callback.cls, "versioning_class", None)
99 if versioning_class is not None and issubclass(
100 versioning_class, versioning.URLPathVersioning
101 ):
102 version = getattr(self.request, "version", None)
103 if version:
104 version_param = getattr(versioning_class, "version_param", "version")
105 version_param = "{%s}" % version_param
106 if version_param not in path:
107 logger.info(
108 "view %s uses URLPathVersioning but URL %s has no param %s"
109 % (callback.cls, path, version_param)
110 )
111 path = path.replace(version_param, version)
112
113 return path
114
115 def get_api_endpoints(
116 self,
117 patterns=None,
118 prefix="",
119 app_name=None,
120 namespace=None,
121 ignored_endpoints=None,
122 ):
123 """
124 Return a list of all available API endpoints by inspecting the URL conf.
125
126 Copied entirely from super.
127 """
128 if patterns is None:
129 patterns = self.patterns
130
131 api_endpoints = []
132 if ignored_endpoints is None:
133 ignored_endpoints = set()
134
135 for pattern in patterns:
136 path_regex = prefix + str(pattern.pattern)
137 if isinstance(pattern, URLPattern):
138 try:
139 path = self.get_path_from_regex(path_regex)
140 callback = pattern.callback
141 url_name = pattern.name
142 if self.should_include_endpoint(
143 path, callback, app_name or "", namespace or "", url_name
144 ):
145 path = self.replace_version(path, callback)
146
147 # avoid adding endpoints that have already been seen,
148 # as Django resolves urls in top-down order
149 if path in ignored_endpoints:
150 continue
151 ignored_endpoints.add(path)
152
153 for method in self.get_allowed_methods(callback):
154 endpoint = (path, method, callback)
155 api_endpoints.append(endpoint)
156 except Exception: # pragma: no cover
157 logger.warning("failed to enumerate view", exc_info=True)
158
159 elif isinstance(pattern, URLResolver):
160 nested_endpoints = self.get_api_endpoints(
161 patterns=pattern.url_patterns,
162 prefix=path_regex,
163 app_name="%s:%s" % (app_name, pattern.app_name)
164 if app_name
165 else pattern.app_name,
166 namespace="%s:%s" % (namespace, pattern.namespace)
167 if namespace
168 else pattern.namespace,
169 ignored_endpoints=ignored_endpoints,
170 )
171 api_endpoints.extend(nested_endpoints)
172 else:
173 logger.warning("unknown pattern type {}".format(type(pattern)))
174
175 api_endpoints = sorted(api_endpoints, key=endpoint_ordering)
176
177 return api_endpoints
178
179 def unescape(self, s):
180 """Unescape all backslash escapes from `s`.
181
182 :param str s: string with backslash escapes
183 :rtype: str
184 """
185 # unlike .replace('\\', ''), this correctly transforms a double backslash into a
186 # single backslash
187 return re.sub(r"\\(.)", r"\1", s)
188
189 def unescape_path(self, path):
190 """Remove backslashes escapes from all path components outside {parameters}.
191 This is needed because ``simplify_regex`` does not handle this correctly.
192
193 **NOTE:** this might destructively affect some url regex patterns that contain
194 metacharacters (e.g. \\w, \\d) outside path parameter groups; if you are in this
195 category, God help you
196
197 :param str path: path possibly containing
198 :return: the unescaped path
199 :rtype: str
200 """
201 clean_path = ""
202 while path:
203 match = PATH_PARAMETER_RE.search(path)
204 if not match:
205 clean_path += self.unescape(path)
206 break
207 clean_path += self.unescape(path[: match.start()])
208 clean_path += match.group()
209 path = path[match.end() :]
210
211 return clean_path
212
213
214 class OpenAPISchemaGenerator:
215 """
216 This class iterates over all registered API endpoints and returns an appropriate
217 OpenAPI 2.0 compliant schema. Method implementations shamelessly stolen and adapted
218 from rest-framework ``SchemaGenerator``.
219 """
220
221 endpoint_enumerator_class = EndpointEnumerator
222 reference_resolver_class = ReferenceResolver
223
224 # Map HTTP methods onto actions.
225 default_mapping = {
226 "get": "retrieve",
227 "post": "create",
228 "put": "update",
229 "patch": "partial_update",
230 "delete": "destroy",
231 }
232
233 def __init__(self, info, version="", url=None, patterns=None, urlconf=None):
234 """
235
236 :param openapi.Info info: information about the API
237 :param str version: API version string; if omitted, `info.default_version` will
238 be used
239 :param str url: API scheme, host and port; if ``None`` is passed and
240 ``DEFAULT_API_URL`` is not set, the url will be inferred from the request
241 made against the schema view, so you should generally not need to set this
242 parameter explicitly; if the empty string is passed, no host and scheme will
243 be emitted
244
245 If `url` is not ``None`` or the empty string, it must be a scheme-absolute
246 uri (i.e. starting with http:// or https://), and any path component is
247 ignored;
248
249 See also:
250 :ref:`documentation on base URL construction <custom-spec-base-url>`
251 :param patterns: if given, only these patterns will be enumerated for inclusion
252 in the API spec
253 :param urlconf: if patterns is not given, use this urlconf to enumerate
254 patterns; if not given, the default urlconf is used
255 """
256 self._gen = SchemaGenerator(
257 info.title, url, info.get("description", ""), patterns, urlconf
258 )
259 self.info = info
260 self.version = version
261 self.consumes = []
262 self.produces = []
263 self.coerce_method_names = api_settings.SCHEMA_COERCE_METHOD_NAMES
264
265 if url is None and swagger_settings.DEFAULT_API_URL is not None:
266 url = swagger_settings.DEFAULT_API_URL
267
268 if url:
269 parsed_url = urlparse.urlparse(url)
270 if parsed_url.scheme not in ("http", "https") or not parsed_url.netloc:
271 raise SwaggerGenerationError("`url` must be an absolute HTTP(S) url")
272 if parsed_url.path:
273 logger.warning(
274 "path component of api base URL %s is ignored; use "
275 "FORCE_SCRIPT_NAME instead" % url
276 )
277 else:
278 self._gen.url = url
279
280 @property
281 def url(self):
282 return self._gen.url
283
284 def get_security_definitions(self):
285 """Get the security schemes for this API. This determines what is usable in
286 security requirements, and helps clients configure their authorization
287 credentials.
288
289 :return: the security schemes usable with this API
290 :rtype: dict[str,dict] or None
291 """
292 security_definitions = swagger_settings.SECURITY_DEFINITIONS
293 if security_definitions is not None:
294 security_definitions = SwaggerDict._as_dict(security_definitions, {})
295
296 return security_definitions
297
298 def get_security_requirements(self, security_definitions):
299 """Get the base (global) security requirements of the API. This is never called
300 if :meth:`.get_security_definitions` returns `None`.
301
302 :param security_definitions: security definitions as returned by
303 :meth:`.get_security_definitions`
304 :return: the security schemes accepted by default
305 :rtype: list[dict[str,list[str]]] or None
306 """
307 security_requirements = swagger_settings.SECURITY_REQUIREMENTS
308 if security_requirements is None:
309 security_requirements = [
310 {security_scheme: []} for security_scheme in security_definitions
311 ]
312
313 security_requirements = [
314 SwaggerDict._as_dict(sr, {}) for sr in security_requirements
315 ]
316 security_requirements = sorted(security_requirements, key=list)
317 return security_requirements
318
319 def get_schema(self, request=None, public=False):
320 """Generate a :class:`.Swagger` object representing the API schema.
321
322 :param request: the request used for filtering accessible endpoints and finding
323 the spec URI
324 :type request: rest_framework.request.Request or None
325 :param bool public: if True, all endpoints are included regardless of access
326 through `request`
327
328 :return: the generated Swagger specification
329 :rtype: openapi.Swagger
330 """
331 endpoints = self.get_endpoints(request)
332 components = self.reference_resolver_class(
333 openapi.SCHEMA_DEFINITIONS, force_init=True
334 )
335 self.consumes = get_consumes(api_settings.DEFAULT_PARSER_CLASSES)
336 self.produces = get_produces(api_settings.DEFAULT_RENDERER_CLASSES)
337 paths, prefix = self.get_paths(endpoints, components, request, public)
338
339 security_definitions = self.get_security_definitions()
340 if security_definitions:
341 security_requirements = self.get_security_requirements(security_definitions)
342 else:
343 security_requirements = None
344
345 url = self.url
346 if url is None and request is not None:
347 url = request.build_absolute_uri()
348
349 return openapi.Swagger(
350 info=self.info,
351 paths=paths,
352 consumes=self.consumes or None,
353 produces=self.produces or None,
354 security_definitions=security_definitions,
355 security=security_requirements,
356 _url=url,
357 _prefix=prefix,
358 _version=self.version,
359 **dict(components),
360 )
361
362 def create_view(self, callback, method, request=None):
363 """Create a view instance from a view callback as registered in urlpatterns.
364
365 :param callback: view callback registered in urlpatterns
366 :param str method: HTTP method
367 :param request: request to bind to the view
368 :type request: rest_framework.request.Request or None
369 :return: the view instance
370 """
371 view = self._gen.create_view(callback, method, request)
372 overrides = getattr(callback, "_swagger_auto_schema", None)
373 if overrides is not None:
374 # decorated function based view must have its decorator information passed
375 # on to the re-instantiated view
376 for method, _ in overrides.items():
377 view_method = getattr(view, method, None)
378 if view_method is not None: # pragma: no cover
379 setattr(view_method.__func__, "_swagger_auto_schema", overrides)
380
381 setattr(view, "swagger_fake_view", True)
382 return view
383
384 def coerce_path(self, path, view):
385 """Coerce {pk} path arguments into the name of the model field, where possible.
386 This is cleaner for an external representation (i.e. "this is an identifier",
387 not "this is a database primary key").
388
389 :param str path: the path
390 :param rest_framework.views.APIView view: associated view
391 :rtype: str
392 """
393 if "{pk}" not in path:
394 return path
395
396 model = getattr(get_queryset_from_view(view), "model", None)
397 if model:
398 field_name = get_pk_name(model)
399 else:
400 field_name = "id"
401 return path.replace("{pk}", "{%s}" % field_name)
402
403 def get_endpoints(self, request):
404 """Iterate over all the registered endpoints in the API and return a fake view
405 with the right parameters.
406
407 :param request: request to bind to the endpoint views
408 :type request: rest_framework.request.Request or None
409 :return: {path: (view_class, list[(http_method, view_instance)])
410 :rtype: dict[str,(type,list[(str,rest_framework.views.APIView)])]
411 """
412 enumerator = self.endpoint_enumerator_class(
413 self._gen.patterns, self._gen.urlconf, request=request
414 )
415 endpoints = enumerator.get_api_endpoints()
416
417 view_paths = defaultdict(list)
418 view_cls = {}
419 for path, method, callback in endpoints:
420 view = self.create_view(callback, method, request)
421 path = self.coerce_path(path, view)
422 view_paths[path].append((method, view))
423 view_cls[path] = callback.cls
424 return {path: (view_cls[path], methods) for path, methods in view_paths.items()}
425
426 def get_operation_keys(self, subpath, method, view):
427 """Return a list of keys that should be used to group an operation within the specification. ::
428
429 /users/ ("users", "list"), ("users", "create")
430 /users/{pk}/ ("users", "read"), ("users", "update"), ("users", "delete")
431 /users/enabled/ ("users", "enabled") # custom viewset list action
432 /users/{pk}/star/ ("users", "star") # custom viewset detail action
433 /users/{pk}/groups/ ("users", "groups", "list"), ("users", "groups", "create")
434 /users/{pk}/groups/{pk}/ ("users", "groups", "read"), ("users", "groups", "update")
435
436 :param str subpath: path to the operation with any common prefix/base path removed
437 :param str method: HTTP method
438 :param view: the view associated with the operation
439 :rtype: list[str]
440 """ # noqa: E501
441 if hasattr(view, "action"):
442 # Viewsets have explicitly named actions.
443 action = view.action
444 else:
445 # Views have no associated action, so we determine one from the method.
446 if is_list_view(subpath, method, view):
447 action = "list"
448 else:
449 action = self.default_mapping[method.lower()]
450
451 named_path_components = [
452 component
453 for component in subpath.strip("/").split("/")
454 if "{" not in component
455 ]
456
457 if is_custom_action(action):
458 # Custom action, eg "/users/{pk}/activate/", "/users/active/"
459 mapped_methods = {
460 # Don't count head mapping, e.g. not part of the schema
461 method
462 for method in view.action_map
463 if method != "head"
464 }
465 if len(mapped_methods) > 1:
466 action = self.default_mapping[method.lower()]
467 if action in self.coerce_method_names:
468 action = self.coerce_method_names[action]
469 return named_path_components + [action]
470 else:
471 return named_path_components[:-1] + [action]
472
473 if action in self.coerce_method_names:
474 action = self.coerce_method_names[action]
475
476 # Default action, eg "/users/", "/users/{pk}/"
477 return named_path_components + [action]
478
479 def determine_path_prefix(self, paths):
480 """
481 Given a list of all paths, return the common prefix which should be
482 discounted when generating a schema structure.
483
484 This will be the longest common string that does not include that last
485 component of the URL, or the last component before a path parameter.
486
487 For example: ::
488
489 /api/v1/users/
490 /api/v1/users/{pk}/
491
492 The path prefix is ``/api/v1/``.
493
494 :param list[str] paths: list of paths
495 :rtype: str
496 """
497 prefixes = []
498 for path in paths:
499 components = path.strip("/").split("/")
500 initial_components = []
501 for component in components:
502 if "{" in component:
503 break
504 initial_components.append(component)
505 prefix = "/".join(initial_components[:-1])
506 if not prefix:
507 # We can just break early in the case that there's at least
508 # one URL that doesn't have a path prefix.
509 return "/"
510 prefixes.append("/" + prefix + "/")
511 return common_path(prefixes)
512
513 def should_include_endpoint(self, path, method, view, public):
514 """Check if a given endpoint should be included in the resulting schema.
515
516 :param str path: request path
517 :param str method: http request method
518 :param view: instantiated view callback
519 :param bool public: if True, all endpoints are included regardless of access
520 through `request`
521 :returns: true if the view should be excluded
522 :rtype: bool
523 """
524 return public or self._gen.has_view_permissions(path, method, view)
525
526 def get_paths_object(self, paths):
527 """Construct the Swagger Paths object.
528
529 :param dict[str,openapi.PathItem] paths: mapping of paths to
530 :class:`.PathItem` objects
531 :returns: the :class:`.Paths` object
532 :rtype: openapi.Paths
533 """
534 return openapi.Paths(paths=paths)
535
536 def get_paths(self, endpoints, components, request, public):
537 """Generate the Swagger Paths for the API from the given endpoints.
538
539 :param dict endpoints: endpoints as returned by get_endpoints
540 :param ReferenceResolver components: resolver/container for Swagger References
541 :param Request request: the request made against the schema view; can be None
542 :param bool public: if True, all endpoints are included regardless of access
543 through `request`
544 :returns: the :class:`.Paths` object and the longest common path prefix, as a
545 2-tuple
546 :rtype: tuple[openapi.Paths,str]
547 """
548 if not endpoints:
549 return openapi.Paths(paths={}), ""
550
551 prefix = self.determine_path_prefix(list(endpoints.keys())) or ""
552 assert "{" not in prefix, "base path cannot be templated in swagger 2.0"
553
554 paths = {}
555 for path, (view_cls, methods) in sorted(endpoints.items()):
556 operations = {}
557 for method, view in methods:
558 if not self.should_include_endpoint(path, method, view, public):
559 continue
560
561 operation = self.get_operation(
562 view, path, prefix, method, components, request
563 )
564 if operation is not None:
565 operations[method.lower()] = operation
566
567 if operations:
568 # since the common prefix is used as the API basePath, it must be
569 # stripped from individual paths when writing them into the swagger
570 # document
571 path_suffix = path[len(prefix) :]
572 if not path_suffix.startswith("/"):
573 path_suffix = "/" + path_suffix
574 paths[path_suffix] = self.get_path_item(path, view_cls, operations)
575
576 return self.get_paths_object(paths), prefix
577
578 def get_operation(self, view, path, prefix, method, components, request):
579 """Get an :class:`.Operation` for the given API endpoint (path, method). This
580 method delegates to :meth:`~.inspectors.ViewInspector.get_operation` of a
581 :class:`~.inspectors.ViewInspector` determined according to settings and
582 :func:`@swagger_auto_schema <.swagger_auto_schema>` overrides.
583
584 :param view: the view associated with this endpoint
585 :param str path: the path component of the operation URL
586 :param str prefix: common path prefix among all endpoints
587 :param str method: the http method of the operation
588 :param openapi.ReferenceResolver components: referenceable components
589 :param Request request: the request made against the schema view; can be None
590 :rtype: openapi.Operation
591 """
592 operation_keys = self.get_operation_keys(path[len(prefix) :], method, view)
593 overrides = self.get_overrides(view, method)
594
595 # the inspector class can be specified, in decreasing order of priority,
596 # 1. globally via DEFAULT_AUTO_SCHEMA_CLASS
597 view_inspector_cls = swagger_settings.DEFAULT_AUTO_SCHEMA_CLASS
598 # 2. on the view/viewset class
599 view_inspector_cls = getattr(view, "swagger_schema", view_inspector_cls)
600 # 3. on the swagger_auto_schema decorator
601 view_inspector_cls = overrides.get("auto_schema", view_inspector_cls)
602
603 if view_inspector_cls is None:
604 return None
605
606 view_inspector = view_inspector_cls(
607 view, path, method, components, request, overrides, operation_keys
608 )
609 operation = view_inspector.get_operation(operation_keys)
610 if operation is None:
611 return None
612
613 if "consumes" in operation and set(operation.consumes) == set(self.consumes):
614 del operation.consumes
615 if "produces" in operation and set(operation.produces) == set(self.produces):
616 del operation.produces
617 return operation
618
619 def get_path_item(self, path, view_cls, operations):
620 """Get a :class:`.PathItem` object that describes the parameters and operations
621 related to a single path in the API.
622
623 :param str path: the path
624 :param type view_cls: the view that was bound to this path in urlpatterns
625 :param dict[str,openapi.Operation] operations: operations defined on this path,
626 keyed by lowercase HTTP method
627 :rtype: openapi.PathItem
628 """
629 path_parameters = self.get_path_parameters(path, view_cls)
630 return openapi.PathItem(parameters=path_parameters, **operations)
631
632 def get_overrides(self, view, method):
633 """Get overrides specified for a given operation.
634
635 :param view: the view associated with the operation
636 :param str method: HTTP method
637 :return: a dictionary containing any overrides set by
638 :func:`@swagger_auto_schema <.swagger_auto_schema>`
639 :rtype: dict
640 """
641 method = method.lower()
642 action = getattr(view, "action", method)
643 action_method = getattr(view, action, None)
644 overrides = getattr(action_method, "_swagger_auto_schema", {})
645 if method in overrides:
646 overrides = overrides[method]
647
648 return copy.deepcopy(overrides)
649
650 def get_path_parameters(self, path, view_cls):
651 """Return a list of Parameter instances corresponding to any templated path
652 variables.
653
654 :param str path: templated request path
655 :param type view_cls: the view class associated with the path
656 :return: path parameters
657 :rtype: list[openapi.Parameter]
658 """
659 parameters = []
660 queryset = get_queryset_from_view(view_cls)
661
662 for variable in uritemplate.variables(path):
663 model, model_field = get_queryset_field(queryset, variable)
664 attrs = get_basic_type_info(model_field) or {"type": openapi.TYPE_STRING}
665 if (
666 getattr(view_cls, "lookup_field", None) == variable
667 and attrs["type"] == openapi.TYPE_STRING
668 ):
669 attrs["pattern"] = getattr(
670 view_cls, "lookup_value_regex", attrs.get("pattern", None)
671 )
672
673 if model_field and getattr(model_field, "help_text", False):
674 description = model_field.help_text
675 elif model_field and getattr(model_field, "primary_key", False):
676 description = get_pk_description(model, model_field)
677 else:
678 description = None
679
680 field = openapi.Parameter(
681 name=variable,
682 description=force_real_str(description),
683 required=True,
684 in_=openapi.IN_PATH,
685 **attrs,
686 )
687 parameters.append(field)
688
689 return parameters