| 1 |
import enum |
| 2 |
import logging |
| 3 |
import re |
| 4 |
import urllib.parse as urlparse |
| 5 |
import warnings |
| 6 |
from collections import abc as collections_abc |
| 7 |
|
| 8 |
from django.urls import get_script_prefix |
| 9 |
from django.utils.functional import Promise |
| 10 |
from inflection import camelize |
| 11 |
|
| 12 |
from .utils import filter_none, force_real_str |
| 13 |
|
| 14 |
logger = logging.getLogger(__name__) |
| 15 |
|
| 16 |
TYPE_OBJECT = "object" |
| 17 |
TYPE_STRING = "string" |
| 18 |
TYPE_NUMBER = "number" |
| 19 |
TYPE_INTEGER = "integer" |
| 20 |
TYPE_BOOLEAN = "boolean" |
| 21 |
TYPE_ARRAY = "array" |
| 22 |
TYPE_FILE = "file" |
| 23 |
|
| 24 |
|
| 25 |
FORMAT_DATE = "date" |
| 26 |
FORMAT_DATETIME = "date-time" |
| 27 |
FORMAT_PASSWORD = "password" |
| 28 |
FORMAT_BINARY = "binary" |
| 29 |
FORMAT_BASE64 = "bytes" |
| 30 |
FORMAT_FLOAT = "float" |
| 31 |
FORMAT_DOUBLE = "double" |
| 32 |
FORMAT_INT32 = "int32" |
| 33 |
FORMAT_INT64 = "int64" |
| 34 |
|
| 35 |
|
| 36 |
FORMAT_EMAIL = "email" |
| 37 |
FORMAT_IPV4 = "ipv4" |
| 38 |
FORMAT_IPV6 = "ipv6" |
| 39 |
FORMAT_URI = "uri" |
| 40 |
|
| 41 |
|
| 42 |
FORMAT_UUID = "uuid" |
| 43 |
FORMAT_SLUG = "slug" |
| 44 |
FORMAT_DECIMAL = "decimal" |
| 45 |
|
| 46 |
IN_BODY = "body" |
| 47 |
IN_PATH = "path" |
| 48 |
IN_QUERY = "query" |
| 49 |
IN_FORM = "formData" |
| 50 |
IN_HEADER = "header" |
| 51 |
|
| 52 |
SCHEMA_DEFINITIONS = "definitions" |
| 53 |
|
| 54 |
|
| 55 |
def make_swagger_name(attribute_name): |
| 56 |
""" |
| 57 |
Convert a python variable name into a Swagger spec attribute name. |
| 58 |
|
| 59 |
In particular, |
| 60 |
* if name starts with ``x_``, return ``x-{camelCase}`` |
| 61 |
* if name is ``ref``, return ``$ref`` |
| 62 |
* else return the name converted to camelCase, with trailing underscores stripped |
| 63 |
|
| 64 |
:param str attribute_name: python attribute name |
| 65 |
:return: swagger name |
| 66 |
""" |
| 67 |
if attribute_name == "ref": |
| 68 |
return "$ref" |
| 69 |
if attribute_name.startswith("x_"): |
| 70 |
return "x-" + camelize(attribute_name[2:], uppercase_first_letter=False) |
| 71 |
return camelize(attribute_name.rstrip("_"), uppercase_first_letter=False) |
| 72 |
|
| 73 |
|
| 74 |
def _bare_SwaggerDict(cls): |
| 75 |
assert issubclass(cls, SwaggerDict) |
| 76 |
result = cls.__new__(cls) |
| 77 |
dict.__init__(result) |
| 78 |
return result |
| 79 |
|
| 80 |
|
| 81 |
class SwaggerDict(dict): |
| 82 |
"""A particular type of dict, which maps all attribute accesses to dict |
| 83 |
lookups using :func:`.make_swagger_name`. Attribute names starting with ``_`` are |
| 84 |
set on the object as-is and are not included in the specification output. |
| 85 |
|
| 86 |
Used as a base class for all Swagger helper models. |
| 87 |
""" |
| 88 |
|
| 89 |
def __init__(self, **attrs): |
| 90 |
super(SwaggerDict, self).__init__() |
| 91 |
self._extras__ = attrs |
| 92 |
if type(self) is SwaggerDict: |
| 93 |
self._insert_extras__() |
| 94 |
|
| 95 |
def __setattr__(self, key, value): |
| 96 |
if key.startswith("_"): |
| 97 |
super(SwaggerDict, self).__setattr__(key, value) |
| 98 |
return |
| 99 |
if value is not None: |
| 100 |
self[make_swagger_name(key)] = value |
| 101 |
|
| 102 |
def __getattr__(self, item): |
| 103 |
if item.startswith("_"): |
| 104 |
raise AttributeError |
| 105 |
try: |
| 106 |
return self[make_swagger_name(item)] |
| 107 |
except KeyError: |
| 108 |
|
| 109 |
raise AttributeError( |
| 110 |
"object of class " + type(self).__name__ + " has no attribute " + item |
| 111 |
) |
| 112 |
|
| 113 |
def __delattr__(self, item): |
| 114 |
if item.startswith("_"): |
| 115 |
super(SwaggerDict, self).__delattr__(item) |
| 116 |
return |
| 117 |
del self[make_swagger_name(item)] |
| 118 |
|
| 119 |
def _insert_extras__(self): |
| 120 |
""" |
| 121 |
From an ordering perspective, it is desired that extra attributes such as vendor |
| 122 |
extensions stay at the bottom of the object. However, python2.7's OrderedDict |
| 123 |
craps out if you try to insert into it before calling init. This means that |
| 124 |
subclasses must call super().__init__ as the first statement of their own |
| 125 |
__init__, which would result in the extra attributes being added first. For this |
| 126 |
reason, we defer the insertion of the attributes and require that subclasses |
| 127 |
call ._insert_extras__ at the end of their __init__ method. |
| 128 |
""" |
| 129 |
for attr, val in sorted(self._extras__.items()): |
| 130 |
setattr(self, attr, val) |
| 131 |
|
| 132 |
@staticmethod |
| 133 |
def _as_dict(obj, memo): |
| 134 |
"""Implementation detail of :meth:`.as_dict`""" |
| 135 |
if id(obj) in memo: |
| 136 |
return memo[id(obj)] |
| 137 |
|
| 138 |
if isinstance(obj, Promise) and hasattr(obj, "_proxy____cast"): |
| 139 |
|
| 140 |
obj = obj._proxy____cast() |
| 141 |
|
| 142 |
if isinstance(obj, collections_abc.Mapping): |
| 143 |
result = {} |
| 144 |
memo[id(obj)] = result |
| 145 |
items = obj.items() |
| 146 |
if not isinstance(obj, dict): |
| 147 |
items = sorted(items) |
| 148 |
for attr, val in items: |
| 149 |
result[SwaggerDict._as_dict(attr, memo)] = SwaggerDict._as_dict( |
| 150 |
val, memo |
| 151 |
) |
| 152 |
return result |
| 153 |
elif isinstance(obj, str): |
| 154 |
return force_real_str(obj) |
| 155 |
elif isinstance(obj, collections_abc.Iterable) and not isinstance( |
| 156 |
obj, collections_abc.Iterator |
| 157 |
): |
| 158 |
return type(obj)(SwaggerDict._as_dict(elem, memo) for elem in obj) |
| 159 |
elif isinstance(obj, enum.Enum): |
| 160 |
return obj.value |
| 161 |
|
| 162 |
return obj |
| 163 |
|
| 164 |
def as_dict(self): |
| 165 |
"""Convert this object into an ``dict`` instance. |
| 166 |
|
| 167 |
:rtype: dict |
| 168 |
""" |
| 169 |
return SwaggerDict._as_dict(self, {}) |
| 170 |
|
| 171 |
def as_odict(self): |
| 172 |
warnings.warn("as_odict has been renamed to as_dict", DeprecationWarning) |
| 173 |
return self.as_dict() |
| 174 |
|
| 175 |
def __reduce__(self): |
| 176 |
|
| 177 |
|
| 178 |
attrs = {k: v for k, v in vars(self).items() if not k.startswith("_NP_")} |
| 179 |
return _bare_SwaggerDict, (type(self),), attrs, None, iter(self.items()) |
| 180 |
|
| 181 |
|
| 182 |
class Contact(SwaggerDict): |
| 183 |
def __init__(self, name=None, url=None, email=None, **extra): |
| 184 |
"""Swagger Contact object |
| 185 |
|
| 186 |
At least one of the following fields is required: |
| 187 |
|
| 188 |
:param str name: contact name |
| 189 |
:param str url: contact url |
| 190 |
:param str email: contact e-mail |
| 191 |
""" |
| 192 |
super(Contact, self).__init__(**extra) |
| 193 |
if name is None and url is None and email is None: |
| 194 |
raise AssertionError( |
| 195 |
"one of name, url or email is requires for Swagger Contact object" |
| 196 |
) |
| 197 |
self.name = name |
| 198 |
self.url = url |
| 199 |
self.email = email |
| 200 |
self._insert_extras__() |
| 201 |
|
| 202 |
|
| 203 |
class License(SwaggerDict): |
| 204 |
def __init__(self, name, url=None, **extra): |
| 205 |
"""Swagger License object |
| 206 |
|
| 207 |
:param str name: Required. License name |
| 208 |
:param str url: link to detailed license information |
| 209 |
""" |
| 210 |
super(License, self).__init__(**extra) |
| 211 |
if name is None: |
| 212 |
raise AssertionError("name is required for Swagger License object") |
| 213 |
self.name = name |
| 214 |
self.url = url |
| 215 |
self._insert_extras__() |
| 216 |
|
| 217 |
|
| 218 |
class Info(SwaggerDict): |
| 219 |
def __init__( |
| 220 |
self, |
| 221 |
title, |
| 222 |
default_version, |
| 223 |
description=None, |
| 224 |
terms_of_service=None, |
| 225 |
contact=None, |
| 226 |
license=None, |
| 227 |
**extra, |
| 228 |
): |
| 229 |
"""Swagger Info object |
| 230 |
|
| 231 |
:param str title: Required. API title. |
| 232 |
:param str default_version: Required. API version string (not to be confused |
| 233 |
with Swagger spec version) |
| 234 |
:param str description: API description; markdown supported |
| 235 |
:param str terms_of_service: API terms of service; should be a URL |
| 236 |
:param Contact contact: contact object |
| 237 |
:param License license: license object |
| 238 |
""" |
| 239 |
super(Info, self).__init__(**extra) |
| 240 |
if title is None or default_version is None: |
| 241 |
raise AssertionError( |
| 242 |
"title and version are required for Swagger info object" |
| 243 |
) |
| 244 |
if contact is not None and not isinstance(contact, Contact): |
| 245 |
raise AssertionError("contact must be a Contact object") |
| 246 |
if license is not None and not isinstance(license, License): |
| 247 |
raise AssertionError("license must be a License object") |
| 248 |
self.title = title |
| 249 |
self._default_version = default_version |
| 250 |
self.description = description |
| 251 |
self.terms_of_service = terms_of_service |
| 252 |
self.contact = contact |
| 253 |
self.license = license |
| 254 |
self._insert_extras__() |
| 255 |
|
| 256 |
|
| 257 |
class Swagger(SwaggerDict): |
| 258 |
def __init__( |
| 259 |
self, |
| 260 |
info=None, |
| 261 |
_url=None, |
| 262 |
_prefix=None, |
| 263 |
_version=None, |
| 264 |
consumes=None, |
| 265 |
produces=None, |
| 266 |
security_definitions=None, |
| 267 |
security=None, |
| 268 |
paths=None, |
| 269 |
definitions=None, |
| 270 |
**extra, |
| 271 |
): |
| 272 |
"""Root Swagger object. |
| 273 |
|
| 274 |
:param Info info: info object |
| 275 |
:param str _url: URL used for setting the API host and scheme |
| 276 |
:param str _prefix: api path prefix to use in setting basePath; this will be |
| 277 |
appended to the wsgi SCRIPT_NAME prefix or Django's FORCE_SCRIPT_NAME if |
| 278 |
applicable |
| 279 |
:param str _version: version string to override Info |
| 280 |
:param dict[str,dict] security_definitions: list of supported authentication |
| 281 |
mechanisms |
| 282 |
:param list[dict[str,list[str]]] security: authentication mechanisms accepted |
| 283 |
globally |
| 284 |
:param list[str] consumes: consumed MIME types; can be overridden in Operation |
| 285 |
:param list[str] produces: produced MIME types; can be overridden in Operation |
| 286 |
:param Paths paths: paths object |
| 287 |
:param dict[str,Schema] definitions: named models |
| 288 |
""" |
| 289 |
super(Swagger, self).__init__(**extra) |
| 290 |
self.swagger = "2.0" |
| 291 |
self.info = info |
| 292 |
self.info.version = _version or info._default_version |
| 293 |
|
| 294 |
if _url: |
| 295 |
url = urlparse.urlparse(_url) |
| 296 |
assert url.netloc and url.scheme, ( |
| 297 |
"if given, url must have both schema and netloc" |
| 298 |
) |
| 299 |
self.host = url.netloc |
| 300 |
self.schemes = [url.scheme] |
| 301 |
|
| 302 |
self.base_path = self.get_base_path(get_script_prefix(), _prefix) |
| 303 |
self.consumes = consumes |
| 304 |
self.produces = produces |
| 305 |
self.security_definitions = filter_none(security_definitions) |
| 306 |
self.security = filter_none(security) |
| 307 |
self.paths = paths |
| 308 |
self.definitions = filter_none(definitions) |
| 309 |
self._insert_extras__() |
| 310 |
|
| 311 |
@classmethod |
| 312 |
def get_base_path(cls, script_prefix, api_prefix): |
| 313 |
"""Determine an appropriate value for ``basePath`` based on the SCRIPT_NAME and |
| 314 |
the api common prefix. |
| 315 |
|
| 316 |
:param str script_prefix: script prefix as defined by django |
| 317 |
``get_script_prefix`` |
| 318 |
:param str api_prefix: api common prefix |
| 319 |
:return: joined base path |
| 320 |
""" |
| 321 |
|
| 322 |
if script_prefix and script_prefix.endswith("/"): |
| 323 |
script_prefix = script_prefix[:-1] |
| 324 |
if not api_prefix.startswith("/"): |
| 325 |
api_prefix = "/" + api_prefix |
| 326 |
|
| 327 |
base_path = script_prefix + api_prefix |
| 328 |
|
| 329 |
|
| 330 |
if base_path and base_path.endswith("/"): |
| 331 |
base_path = base_path[:-1] |
| 332 |
if not base_path.startswith("/"): |
| 333 |
base_path = "/" + base_path |
| 334 |
|
| 335 |
return base_path |
| 336 |
|
| 337 |
|
| 338 |
class Paths(SwaggerDict): |
| 339 |
def __init__(self, paths, **extra): |
| 340 |
"""A listing of all the paths in the API. |
| 341 |
|
| 342 |
:param dict[str,PathItem] paths: |
| 343 |
""" |
| 344 |
super(Paths, self).__init__(**extra) |
| 345 |
for path, path_obj in paths.items(): |
| 346 |
assert path.startswith("/") |
| 347 |
if path_obj is not None: |
| 348 |
self[path] = path_obj |
| 349 |
self._insert_extras__() |
| 350 |
|
| 351 |
|
| 352 |
class PathItem(SwaggerDict): |
| 353 |
OPERATION_NAMES = ["get", "put", "post", "delete", "options", "head", "patch"] |
| 354 |
|
| 355 |
def __init__( |
| 356 |
self, |
| 357 |
get=None, |
| 358 |
put=None, |
| 359 |
post=None, |
| 360 |
delete=None, |
| 361 |
options=None, |
| 362 |
head=None, |
| 363 |
patch=None, |
| 364 |
parameters=None, |
| 365 |
**extra, |
| 366 |
): |
| 367 |
"""Information about a single path |
| 368 |
|
| 369 |
:param Operation get: operation for GET |
| 370 |
:param Operation put: operation for PUT |
| 371 |
:param Operation post: operation for POST |
| 372 |
:param Operation delete: operation for DELETE |
| 373 |
:param Operation options: operation for OPTIONS |
| 374 |
:param Operation head: operation for HEAD |
| 375 |
:param Operation patch: operation for PATCH |
| 376 |
:param list[Parameter] parameters: parameters that apply to all operations |
| 377 |
""" |
| 378 |
super(PathItem, self).__init__(**extra) |
| 379 |
self.get = get |
| 380 |
self.head = head |
| 381 |
self.post = post |
| 382 |
self.put = put |
| 383 |
self.patch = patch |
| 384 |
self.delete = delete |
| 385 |
self.options = options |
| 386 |
self.parameters = filter_none(parameters) |
| 387 |
self._insert_extras__() |
| 388 |
|
| 389 |
@property |
| 390 |
def operations(self): |
| 391 |
"""A list of all standard Operations on this PathItem object. See |
| 392 |
:attr:`.OPERATION_NAMES`. |
| 393 |
|
| 394 |
:return: list of (method name, Operation) tuples |
| 395 |
:rtype: list[tuple[str,Operation]] |
| 396 |
""" |
| 397 |
return [(k, v) for k, v in self.items() if k in PathItem.OPERATION_NAMES and v] |
| 398 |
|
| 399 |
|
| 400 |
class Operation(SwaggerDict): |
| 401 |
def __init__( |
| 402 |
self, |
| 403 |
operation_id, |
| 404 |
responses, |
| 405 |
parameters=None, |
| 406 |
consumes=None, |
| 407 |
produces=None, |
| 408 |
summary=None, |
| 409 |
description=None, |
| 410 |
tags=None, |
| 411 |
security=None, |
| 412 |
**extra, |
| 413 |
): |
| 414 |
"""Information about an API operation (path + http method combination) |
| 415 |
|
| 416 |
:param str operation_id: operation ID, should be unique across all operations |
| 417 |
:param Responses responses: responses returned |
| 418 |
:param list[Parameter] parameters: parameters accepted |
| 419 |
:param list[str] consumes: content types accepted |
| 420 |
:param list[str] produces: content types produced |
| 421 |
:param str summary: operation summary; should be < 120 characters |
| 422 |
:param str description: operation description; can be of any length and supports |
| 423 |
markdown |
| 424 |
:param list[str] tags: operation tags |
| 425 |
:param list[dict[str,list[str]]] security: list of security requirements |
| 426 |
""" |
| 427 |
super(Operation, self).__init__(**extra) |
| 428 |
self.operation_id = operation_id |
| 429 |
self.summary = summary |
| 430 |
self.description = description |
| 431 |
self.parameters = filter_none(parameters) |
| 432 |
self.responses = responses |
| 433 |
self.consumes = filter_none(consumes) |
| 434 |
self.produces = filter_none(produces) |
| 435 |
self.tags = filter_none(tags) |
| 436 |
self.security = filter_none(security) |
| 437 |
self._insert_extras__() |
| 438 |
|
| 439 |
|
| 440 |
def _check_type(type, format, enum, pattern, items, _obj_type): |
| 441 |
if items and type != TYPE_ARRAY: |
| 442 |
raise AssertionError("items can only be used when type is array") |
| 443 |
if type == TYPE_ARRAY and not items: |
| 444 |
raise AssertionError("TYPE_ARRAY requires the items attribute") |
| 445 |
if pattern and type != TYPE_STRING: |
| 446 |
raise AssertionError("pattern can only be used when type is string") |
| 447 |
if (format or enum or pattern) and type in (TYPE_OBJECT, TYPE_ARRAY, None): |
| 448 |
raise AssertionError( |
| 449 |
"[format, enum, pattern] can only be applied to primitive " + _obj_type |
| 450 |
) |
| 451 |
|
| 452 |
|
| 453 |
class Items(SwaggerDict): |
| 454 |
def __init__( |
| 455 |
self, type=None, format=None, enum=None, pattern=None, items=None, **extra |
| 456 |
): |
| 457 |
"""Used when defining an array :class:`.Parameter` to describe the array |
| 458 |
elements. |
| 459 |
|
| 460 |
:param str type: type of the array elements; must not be ``object`` |
| 461 |
:param str format: value format, see OpenAPI spec |
| 462 |
:param list enum: restrict possible values |
| 463 |
:param str pattern: pattern if type is ``string`` |
| 464 |
:param Items items: only valid if `type` is ``array`` |
| 465 |
""" |
| 466 |
super(Items, self).__init__(**extra) |
| 467 |
assert type is not None, "type is required!" |
| 468 |
self.type = type |
| 469 |
self.format = format |
| 470 |
self.enum = enum |
| 471 |
self.pattern = pattern |
| 472 |
self.items_ = items |
| 473 |
self._insert_extras__() |
| 474 |
_check_type(type, format, enum, pattern, items, self.__class__) |
| 475 |
|
| 476 |
|
| 477 |
class Parameter(SwaggerDict): |
| 478 |
def __init__( |
| 479 |
self, |
| 480 |
name, |
| 481 |
in_, |
| 482 |
description=None, |
| 483 |
required=None, |
| 484 |
schema=None, |
| 485 |
type=None, |
| 486 |
format=None, |
| 487 |
enum=None, |
| 488 |
pattern=None, |
| 489 |
items=None, |
| 490 |
default=None, |
| 491 |
**extra, |
| 492 |
): |
| 493 |
"""Describe parameters accepted by an :class:`.Operation`. Each parameter should |
| 494 |
be a unique combination of (`name`, `in_`). ``body`` and ``form`` parameters in |
| 495 |
the same operation are mutually exclusive. |
| 496 |
|
| 497 |
:param str name: parameter name |
| 498 |
:param str in_: parameter location |
| 499 |
:param str description: parameter description |
| 500 |
:param bool required: whether the parameter is required for the operation |
| 501 |
:param schema: required if `in_` is ``body`` |
| 502 |
:type schema: Schema or SchemaRef |
| 503 |
:param str type: parameter type; required if `in_` is not ``body``; must not be |
| 504 |
``object`` |
| 505 |
:param str format: value format, see OpenAPI spec |
| 506 |
:param list enum: restrict possible values |
| 507 |
:param str pattern: pattern if type is ``string`` |
| 508 |
:param Items items: only valid if `type` is ``array`` |
| 509 |
:param default: default value if the parameter is not provided; must conform to |
| 510 |
parameter type |
| 511 |
""" |
| 512 |
super(Parameter, self).__init__(**extra) |
| 513 |
self.name = name |
| 514 |
self.in_ = in_ |
| 515 |
self.description = description |
| 516 |
self.required = required |
| 517 |
self.schema = schema |
| 518 |
self.type = type |
| 519 |
self.format = format |
| 520 |
self.enum = enum |
| 521 |
self.pattern = pattern |
| 522 |
self.items_ = items |
| 523 |
self.default = default |
| 524 |
self._insert_extras__() |
| 525 |
if (not schema and not type) or (schema and type): |
| 526 |
raise AssertionError( |
| 527 |
"either schema or type are required for Parameter object (not both)!" |
| 528 |
) |
| 529 |
if schema and isinstance(schema, Schema): |
| 530 |
schema._remove_read_only() |
| 531 |
if self["in"] == IN_PATH: |
| 532 |
|
| 533 |
assert required is not False, "path parameter cannot be optional" |
| 534 |
self.required = True |
| 535 |
if self["in"] != IN_BODY and schema is not None: |
| 536 |
raise AssertionError( |
| 537 |
"schema can only be applied to a body Parameter, not %s" % type |
| 538 |
) |
| 539 |
if default and not type: |
| 540 |
raise AssertionError("default can only be applied to a non-body Parameter") |
| 541 |
_check_type(type, format, enum, pattern, items, self.__class__) |
| 542 |
|
| 543 |
|
| 544 |
class Schema(SwaggerDict): |
| 545 |
|
| 546 |
OR_REF = () |
| 547 |
|
| 548 |
def __init__( |
| 549 |
self, |
| 550 |
title=None, |
| 551 |
description=None, |
| 552 |
type=None, |
| 553 |
format=None, |
| 554 |
enum=None, |
| 555 |
pattern=None, |
| 556 |
properties=None, |
| 557 |
additional_properties=None, |
| 558 |
required=None, |
| 559 |
items=None, |
| 560 |
default=None, |
| 561 |
read_only=None, |
| 562 |
**extra, |
| 563 |
): |
| 564 |
"""Describes a complex object accepted as parameter or returned as a response. |
| 565 |
|
| 566 |
:param str title: schema title |
| 567 |
:param str description: schema description |
| 568 |
:param str type: value type; required |
| 569 |
:param str format: value format, see OpenAPI spec |
| 570 |
:param list enum: restrict possible values |
| 571 |
:param str pattern: pattern if type is ``string`` |
| 572 |
:param properties: object properties; required if `type` is ``object`` |
| 573 |
:type properties: dict[str,Schema or SchemaRef] |
| 574 |
:param additional_properties: allow wildcard properties not listed in |
| 575 |
`properties` |
| 576 |
:type additional_properties: bool or Schema or SchemaRef |
| 577 |
:param list[str] required: list of required property names |
| 578 |
:param items: type of array items, only valid if `type` is ``array`` |
| 579 |
:type items: Schema or SchemaRef |
| 580 |
:param default: only valid when insider another ``Schema``\\ 's ``properties``; |
| 581 |
the default value of this property if it is not provided, must conform to |
| 582 |
the type of this Schema |
| 583 |
:param read_only: only valid when insider another ``Schema``\\ 's |
| 584 |
``properties``; declares the property as read only - it must only be sent |
| 585 |
as part of responses, never in requests |
| 586 |
""" |
| 587 |
super(Schema, self).__init__(**extra) |
| 588 |
if required is True or required is False: |
| 589 |
|
| 590 |
raise AssertionError( |
| 591 |
"the `required` attribute of schema must be an " |
| 592 |
"array of required property names, not a boolean!" |
| 593 |
) |
| 594 |
assert type, "type is required!" |
| 595 |
self.title = title |
| 596 |
self.description = description |
| 597 |
self.required = filter_none(required) |
| 598 |
self.type = type |
| 599 |
self.properties = filter_none(properties) |
| 600 |
self.additional_properties = additional_properties |
| 601 |
self.format = format |
| 602 |
self.enum = enum |
| 603 |
self.pattern = pattern |
| 604 |
self.items_ = items |
| 605 |
self.read_only = read_only |
| 606 |
self.default = default |
| 607 |
self._insert_extras__() |
| 608 |
if (properties or (additional_properties is not None)) and type != TYPE_OBJECT: |
| 609 |
raise AssertionError("only object Schema can have properties") |
| 610 |
_check_type(type, format, enum, pattern, items, self.__class__) |
| 611 |
|
| 612 |
def _remove_read_only(self): |
| 613 |
|
| 614 |
|
| 615 |
self.pop("readOnly", "") |
| 616 |
|
| 617 |
|
| 618 |
class _Ref(SwaggerDict): |
| 619 |
ref_name_re = re.compile(r"#/(?P<scope>.+)/(?P<name>[^/]+)$") |
| 620 |
|
| 621 |
def __init__(self, resolver, name, scope, expected_type, ignore_unresolved=False): |
| 622 |
"""Base class for all reference types. A reference object has only one property, |
| 623 |
``$ref``, which must be a JSON reference to a valid object in the specification, |
| 624 |
e.g. ``#/definitions/Article`` to refer to an article model. |
| 625 |
|
| 626 |
:param ReferenceResolver resolver: component resolver which must contain the |
| 627 |
referenced object |
| 628 |
:param str name: referenced object name, e.g. "Article" |
| 629 |
:param str scope: reference scope, e.g. "definitions" |
| 630 |
:param type[SwaggerDict] expected_type: the expected type that will be asserted |
| 631 |
on the object found in resolver |
| 632 |
:param bool ignore_unresolved: do not throw if the referenced object does not |
| 633 |
exist |
| 634 |
""" |
| 635 |
super(_Ref, self).__init__() |
| 636 |
assert type(self) is not _Ref, "do not instantiate _Ref directly" |
| 637 |
ref_name = "#/{scope}/{name}".format(scope=scope, name=name) |
| 638 |
if not ignore_unresolved: |
| 639 |
obj = resolver.get(name, scope) |
| 640 |
assert isinstance(obj, expected_type), ( |
| 641 |
ref_name |
| 642 |
+ " is a {actual}, not a {expected}".format( |
| 643 |
actual=type(obj).__name__, expected=expected_type.__name__ |
| 644 |
) |
| 645 |
) |
| 646 |
self.ref = ref_name |
| 647 |
|
| 648 |
def resolve(self, resolver): |
| 649 |
"""Get the object targeted by this reference from the given component resolver. |
| 650 |
|
| 651 |
:param ReferenceResolver resolver: component resolver which must contain the |
| 652 |
referenced object |
| 653 |
:returns: the target object |
| 654 |
""" |
| 655 |
ref_match = self.ref_name_re.match(self.ref) |
| 656 |
return resolver.getdefault( |
| 657 |
ref_match.group("name"), scope=ref_match.group("scope") |
| 658 |
) |
| 659 |
|
| 660 |
def __setitem__(self, key, value): |
| 661 |
if key == "$ref": |
| 662 |
return super(_Ref, self).__setitem__(key, value) |
| 663 |
raise NotImplementedError( |
| 664 |
"only $ref can be set on Reference objects (not %s)" % key |
| 665 |
) |
| 666 |
|
| 667 |
def __delitem__(self, key): |
| 668 |
raise NotImplementedError("cannot delete property of Reference object") |
| 669 |
|
| 670 |
|
| 671 |
class SchemaRef(_Ref): |
| 672 |
def __init__(self, resolver, schema_name, ignore_unresolved=False): |
| 673 |
"""Adds a reference to a named Schema defined in the ``#/definitions/`` object. |
| 674 |
|
| 675 |
:param ReferenceResolver resolver: component resolver which must contain the |
| 676 |
definition |
| 677 |
:param str schema_name: schema name |
| 678 |
:param bool ignore_unresolved: do not throw if the referenced object does not |
| 679 |
exist |
| 680 |
""" |
| 681 |
assert SCHEMA_DEFINITIONS in resolver.scopes |
| 682 |
super(SchemaRef, self).__init__( |
| 683 |
resolver, schema_name, SCHEMA_DEFINITIONS, Schema, ignore_unresolved |
| 684 |
) |
| 685 |
|
| 686 |
|
| 687 |
Schema.OR_REF = (Schema, SchemaRef) |
| 688 |
|
| 689 |
|
| 690 |
def resolve_ref(ref_or_obj, resolver): |
| 691 |
"""Resolve `ref_or_obj` if it is a reference type. Return it unchanged if not. |
| 692 |
|
| 693 |
:param ref_or_obj: object to dereference |
| 694 |
:type ref_or_obj: SwaggerDict or _Ref |
| 695 |
:param resolver: component resolver which must contain the referenced object |
| 696 |
""" |
| 697 |
if isinstance(ref_or_obj, _Ref): |
| 698 |
return ref_or_obj.resolve(resolver) |
| 699 |
return ref_or_obj |
| 700 |
|
| 701 |
|
| 702 |
class Responses(SwaggerDict): |
| 703 |
def __init__(self, responses, default=None, **extra): |
| 704 |
"""Describes the expected responses of an :class:`.Operation`. |
| 705 |
|
| 706 |
:param responses: mapping of status code to response definition |
| 707 |
:type responses: dict[str or int,Response] |
| 708 |
:param Response default: description of the response structure to expect if |
| 709 |
another status code is returned |
| 710 |
""" |
| 711 |
super(Responses, self).__init__(**extra) |
| 712 |
for status, response in responses.items(): |
| 713 |
if response is not None: |
| 714 |
self[str(status)] = response |
| 715 |
self.default = default |
| 716 |
self._insert_extras__() |
| 717 |
|
| 718 |
|
| 719 |
class Response(SwaggerDict): |
| 720 |
def __init__(self, description, schema=None, examples=None, **extra): |
| 721 |
"""Describes the structure of an operation's response. |
| 722 |
|
| 723 |
:param str description: response description |
| 724 |
:param schema: structure of the response body |
| 725 |
:type schema: Schema or SchemaRef or rest_framework.serializers.Serializer |
| 726 |
or type[rest_framework.serializers.Serializer] |
| 727 |
:param dict examples: example bodies mapped by mime type |
| 728 |
""" |
| 729 |
super(Response, self).__init__(**extra) |
| 730 |
self.description = description |
| 731 |
self.schema = schema |
| 732 |
self.examples = examples |
| 733 |
self._insert_extras__() |
| 734 |
if schema and isinstance(schema, Schema): |
| 735 |
schema._remove_read_only() |
| 736 |
|
| 737 |
|
| 738 |
class ReferenceResolver(object): |
| 739 |
"""A mapping type intended for storing objects pointed at by Swagger Refs. |
| 740 |
Provides support and checks for different reference scopes, e.g. 'definitions'. |
| 741 |
|
| 742 |
For example: |
| 743 |
|
| 744 |
:: |
| 745 |
|
| 746 |
> components = ReferenceResolver('definitions', 'parameters') |
| 747 |
> definitions = components.with_scope('definitions') |
| 748 |
> definitions.set('Article', Schema(...)) |
| 749 |
> print(components) |
| 750 |
{'definitions': {'Article': Schema(...)}, 'parameters': {}} |
| 751 |
""" |
| 752 |
|
| 753 |
def __init__(self, *scopes, **kwargs): |
| 754 |
""" |
| 755 |
:param str scopes: an enumeration of the valid scopes this resolver will contain |
| 756 |
""" |
| 757 |
force_init = kwargs.pop("force_init", False) |
| 758 |
if not force_init: |
| 759 |
raise AssertionError( |
| 760 |
"Creating an instance of ReferenceResolver almost certainly won't do" |
| 761 |
"what you want it to do.\n" |
| 762 |
"See https://github.com/axnsan12/drf-yasg/issues/211, " |
| 763 |
"https://github.com/axnsan12/drf-yasg/issues/271, " |
| 764 |
"https://github.com/axnsan12/drf-yasg/issues/325.\n" |
| 765 |
"Pass `force_init=True` to override this." |
| 766 |
) |
| 767 |
|
| 768 |
self._objects = {} |
| 769 |
self._force_scope = None |
| 770 |
for scope in scopes: |
| 771 |
assert isinstance(scope, str), "scope names must be strings" |
| 772 |
self._objects[scope] = {} |
| 773 |
|
| 774 |
def with_scope(self, scope): |
| 775 |
"""Return a view into this :class:`.ReferenceResolver` whose scope is defaulted |
| 776 |
and forced to `scope`. |
| 777 |
|
| 778 |
:param str scope: target scope, must be in this resolver's `scopes` |
| 779 |
:return: the bound resolver |
| 780 |
:rtype: ReferenceResolver |
| 781 |
""" |
| 782 |
assert scope in self.scopes, "unknown scope %s" % scope |
| 783 |
ret = ReferenceResolver(force_init=True) |
| 784 |
ret._objects = self._objects |
| 785 |
ret._force_scope = scope |
| 786 |
return ret |
| 787 |
|
| 788 |
def _check_scope(self, scope): |
| 789 |
real_scope = self._force_scope or scope |
| 790 |
if scope is not None: |
| 791 |
assert not self._force_scope or scope == self._force_scope, ( |
| 792 |
"cannot override forced scope" |
| 793 |
) |
| 794 |
assert real_scope and real_scope in self._objects, "invalid scope %s" % scope |
| 795 |
return real_scope |
| 796 |
|
| 797 |
def set(self, name, obj, scope=None): |
| 798 |
"""Set an object in the given scope, raise an error if it already exists. |
| 799 |
|
| 800 |
:param str name: reference name |
| 801 |
:param obj: referenced object |
| 802 |
:param str scope: reference scope |
| 803 |
""" |
| 804 |
scope = self._check_scope(scope) |
| 805 |
assert obj is not None, "referenced objects cannot be None/null" |
| 806 |
assert name not in self._objects[scope], "#/%s/%s already exists" % ( |
| 807 |
scope, |
| 808 |
name, |
| 809 |
) |
| 810 |
self._objects[scope][name] = obj |
| 811 |
|
| 812 |
def setdefault(self, name, maker, scope=None): |
| 813 |
"""Set an object in the given scope only if it does not exist. |
| 814 |
|
| 815 |
:param str name: reference name |
| 816 |
:param function maker: object factory, called only if necessary |
| 817 |
:param str scope: reference scope |
| 818 |
""" |
| 819 |
scope = self._check_scope(scope) |
| 820 |
assert callable(maker), ( |
| 821 |
"setdefault expects a callable, not %s" % type(maker).__name__ |
| 822 |
) |
| 823 |
ret = self.getdefault(name, None, scope) |
| 824 |
if ret is None: |
| 825 |
ret = maker() |
| 826 |
value = self.getdefault(name, None, scope) |
| 827 |
assert ret is not None, ( |
| 828 |
"maker returned None; referenced objects cannot be None/null" |
| 829 |
) |
| 830 |
if value is None: |
| 831 |
self.set(name, ret, scope) |
| 832 |
elif value != ret: |
| 833 |
logger.debug( |
| 834 |
"during setdefault, maker for %s inserted a value and returned a " |
| 835 |
"different value", |
| 836 |
name, |
| 837 |
) |
| 838 |
ret = value |
| 839 |
|
| 840 |
return ret |
| 841 |
|
| 842 |
def get(self, name, scope=None): |
| 843 |
"""Get an object from the given scope, raise an error if it does not exist. |
| 844 |
|
| 845 |
:param str name: reference name |
| 846 |
:param str scope: reference scope |
| 847 |
:return: the object |
| 848 |
""" |
| 849 |
scope = self._check_scope(scope) |
| 850 |
assert name in self._objects[scope], "#/%s/%s is not defined" % (scope, name) |
| 851 |
return self._objects[scope][name] |
| 852 |
|
| 853 |
def getdefault(self, name, default=None, scope=None): |
| 854 |
"""Get an object from the given scope or a default value if it does not exist. |
| 855 |
|
| 856 |
:param str name: reference name |
| 857 |
:param default: the default value |
| 858 |
:param str scope: reference scope |
| 859 |
:return: the object or `default` |
| 860 |
""" |
| 861 |
scope = self._check_scope(scope) |
| 862 |
return self._objects[scope].get(name, default) |
| 863 |
|
| 864 |
def has(self, name, scope=None): |
| 865 |
"""Check if an object exists in the given scope. |
| 866 |
|
| 867 |
:param str name: reference name |
| 868 |
:param str scope: reference scope |
| 869 |
:return: True if the object exists |
| 870 |
:rtype: bool |
| 871 |
""" |
| 872 |
scope = self._check_scope(scope) |
| 873 |
return name in self._objects[scope] |
| 874 |
|
| 875 |
def __iter__(self): |
| 876 |
if self._force_scope: |
| 877 |
return iter(self._objects[self._force_scope]) |
| 878 |
return iter(self._objects) |
| 879 |
|
| 880 |
@property |
| 881 |
def scopes(self): |
| 882 |
if self._force_scope: |
| 883 |
return [self._force_scope] |
| 884 |
return list(self._objects.keys()) |
| 885 |
|
| 886 |
|
| 887 |
def keys(self): |
| 888 |
if self._force_scope: |
| 889 |
return self._objects[self._force_scope].keys() |
| 890 |
return self._objects.keys() |
| 891 |
|
| 892 |
def __getitem__(self, item): |
| 893 |
if self._force_scope: |
| 894 |
return self._objects[self._force_scope][item] |
| 895 |
return self._objects[item] |
| 896 |
|
| 897 |
def __str__(self): |
| 898 |
return str(dict(self)) |