| 1 |
import itertools |
| 2 |
import re |
| 3 |
from http.client import responses |
| 4 |
from typing import TYPE_CHECKING, Any, Dict, Generator, List, Optional, Set, Tuple |
| 5 |
|
| 6 |
from django.utils.termcolors import make_style |
| 7 |
from pydantic.json_schema import JsonSchemaMode |
| 8 |
|
| 9 |
from ninja.constants import NOT_SET |
| 10 |
from ninja.operation import Operation |
| 11 |
from ninja.params.models import TModel, TModels |
| 12 |
from ninja.schema import NinjaGenerateJsonSchema |
| 13 |
from ninja.types import DictStrAny |
| 14 |
from ninja.utils import normalize_path |
| 15 |
|
| 16 |
if TYPE_CHECKING: |
| 17 |
from ninja import NinjaAPI |
| 18 |
|
| 19 |
REF_TEMPLATE: str = "#/components/schemas/{model}" |
| 20 |
|
| 21 |
BODY_CONTENT_TYPES: Dict[str, str] = { |
| 22 |
"body": "application/json", |
| 23 |
"form": "application/x-www-form-urlencoded", |
| 24 |
"file": "multipart/form-data", |
| 25 |
} |
| 26 |
|
| 27 |
|
| 28 |
def get_schema(api: "NinjaAPI", path_prefix: str = "") -> "OpenAPISchema": |
| 29 |
openapi = OpenAPISchema(api, path_prefix) |
| 30 |
return openapi |
| 31 |
|
| 32 |
|
| 33 |
bold_red_style = make_style(opts=("bold",), fg="red") |
| 34 |
|
| 35 |
|
| 36 |
class OpenAPISchema(dict): |
| 37 |
def __init__(self, api: "NinjaAPI", path_prefix: str) -> None: |
| 38 |
self.api = api |
| 39 |
self.path_prefix = path_prefix |
| 40 |
self.schemas: DictStrAny = {} |
| 41 |
self.securitySchemes: DictStrAny = {} |
| 42 |
self.all_operation_ids: Set = set() |
| 43 |
extra_info = api.openapi_extra.get("info", {}) |
| 44 |
super().__init__([ |
| 45 |
("openapi", "3.1.0"), |
| 46 |
( |
| 47 |
"info", |
| 48 |
{ |
| 49 |
"title": api.title, |
| 50 |
"version": api.version, |
| 51 |
"description": api.description, |
| 52 |
**extra_info, |
| 53 |
}, |
| 54 |
), |
| 55 |
("paths", self.get_paths()), |
| 56 |
("components", self.get_components()), |
| 57 |
("servers", api.servers), |
| 58 |
]) |
| 59 |
for k, v in api.openapi_extra.items(): |
| 60 |
if k not in self: |
| 61 |
self[k] = v |
| 62 |
|
| 63 |
def get_paths(self) -> DictStrAny: |
| 64 |
result: DictStrAny = {} |
| 65 |
|
| 66 |
for bound_router in self.api._get_bound_routers(): |
| 67 |
for path, path_view in bound_router.path_operations.items(): |
| 68 |
full_path = "/".join([i for i in (bound_router.prefix, path) if i]) |
| 69 |
full_path = "/" + self.path_prefix + full_path |
| 70 |
full_path = normalize_path(full_path) |
| 71 |
full_path = re.sub( |
| 72 |
r"{[^}:]+:", "{", full_path |
| 73 |
) |
| 74 |
path_methods = self.methods(path_view.operations) |
| 75 |
if path_methods: |
| 76 |
try: |
| 77 |
result[full_path].update(path_methods) |
| 78 |
except KeyError: |
| 79 |
result[full_path] = path_methods |
| 80 |
|
| 81 |
return result |
| 82 |
|
| 83 |
def methods(self, operations: list) -> DictStrAny: |
| 84 |
result = {} |
| 85 |
for op in operations: |
| 86 |
if op.include_in_schema: |
| 87 |
operation_details = self.operation_details(op) |
| 88 |
for method in op.methods: |
| 89 |
result[method.lower()] = operation_details |
| 90 |
return result |
| 91 |
|
| 92 |
def deep_dict_update( |
| 93 |
self, main_dict: Dict[Any, Any], update_dict: Dict[Any, Any] |
| 94 |
) -> None: |
| 95 |
for key in update_dict: |
| 96 |
if ( |
| 97 |
key in main_dict |
| 98 |
and isinstance(main_dict[key], dict) |
| 99 |
and isinstance(update_dict[key], dict) |
| 100 |
): |
| 101 |
self.deep_dict_update( |
| 102 |
main_dict[key], update_dict[key] |
| 103 |
) |
| 104 |
elif ( |
| 105 |
key in main_dict |
| 106 |
and isinstance(main_dict[key], list) |
| 107 |
and isinstance(update_dict[key], list) |
| 108 |
): |
| 109 |
main_dict[key].extend(update_dict[key]) |
| 110 |
else: |
| 111 |
main_dict[key] = update_dict[key] |
| 112 |
|
| 113 |
def operation_details(self, operation: Operation) -> DictStrAny: |
| 114 |
op_id = operation.operation_id or self.api.get_openapi_operation_id(operation) |
| 115 |
if op_id in self.all_operation_ids: |
| 116 |
print( |
| 117 |
bold_red_style( |
| 118 |
f'Warning: operation_id "{op_id}" is already used (Try giving a different name to: {operation.view_func.__module__}.{operation.view_func.__name__})' |
| 119 |
) |
| 120 |
) |
| 121 |
self.all_operation_ids.add(op_id) |
| 122 |
result = { |
| 123 |
"operationId": op_id, |
| 124 |
"summary": operation.summary, |
| 125 |
"parameters": self.operation_parameters(operation), |
| 126 |
"responses": self.responses(operation), |
| 127 |
} |
| 128 |
|
| 129 |
if operation.description: |
| 130 |
result["description"] = operation.description |
| 131 |
|
| 132 |
if operation.tags: |
| 133 |
result["tags"] = operation.tags |
| 134 |
|
| 135 |
if operation.deprecated: |
| 136 |
result["deprecated"] = operation.deprecated |
| 137 |
|
| 138 |
body = self.request_body(operation) |
| 139 |
if body: |
| 140 |
result["requestBody"] = body |
| 141 |
|
| 142 |
security = self.operation_security(operation) |
| 143 |
if security: |
| 144 |
result["security"] = security |
| 145 |
|
| 146 |
if operation.openapi_extra: |
| 147 |
self.deep_dict_update(result, operation.openapi_extra) |
| 148 |
|
| 149 |
return result |
| 150 |
|
| 151 |
def operation_parameters(self, operation: Operation) -> List[DictStrAny]: |
| 152 |
result = [] |
| 153 |
for model in operation.models: |
| 154 |
if model.__ninja_param_source__ not in BODY_CONTENT_TYPES: |
| 155 |
result.extend(self._extract_parameters(model)) |
| 156 |
return result |
| 157 |
|
| 158 |
def _extract_parameters(self, model: TModel) -> List[DictStrAny]: |
| 159 |
result = [] |
| 160 |
|
| 161 |
schema = model.model_json_schema( |
| 162 |
ref_template=REF_TEMPLATE, |
| 163 |
schema_generator=NinjaGenerateJsonSchema, |
| 164 |
) |
| 165 |
|
| 166 |
required = set(schema.get("required", [])) |
| 167 |
properties = schema["properties"] |
| 168 |
|
| 169 |
if "$defs" in schema: |
| 170 |
self.add_schema_definitions(schema["$defs"]) |
| 171 |
|
| 172 |
for name, details in properties.items(): |
| 173 |
is_required = name in required |
| 174 |
p_name: str |
| 175 |
p_schema: DictStrAny |
| 176 |
p_required: bool |
| 177 |
for p_name, p_schema, p_required in flatten_properties( |
| 178 |
name, details, is_required, schema.get("$defs", {}) |
| 179 |
): |
| 180 |
if not p_schema.get("include_in_schema", True): |
| 181 |
continue |
| 182 |
|
| 183 |
param = { |
| 184 |
"in": model.__ninja_param_source__, |
| 185 |
"name": p_name, |
| 186 |
"schema": p_schema, |
| 187 |
"required": p_required, |
| 188 |
} |
| 189 |
|
| 190 |
|
| 191 |
if "description" in p_schema: |
| 192 |
param["description"] = p_schema["description"] |
| 193 |
if "examples" in p_schema: |
| 194 |
param["examples"] = p_schema["examples"] |
| 195 |
elif "example" in p_schema: |
| 196 |
param["example"] = p_schema["example"] |
| 197 |
if "deprecated" in p_schema: |
| 198 |
param["deprecated"] = p_schema["deprecated"] |
| 199 |
|
| 200 |
result.append(param) |
| 201 |
|
| 202 |
return result |
| 203 |
|
| 204 |
def _flatten_schema(self, model: TModel) -> DictStrAny: |
| 205 |
params = self._extract_parameters(model) |
| 206 |
flattened = { |
| 207 |
"title": model.__name__, |
| 208 |
"type": "object", |
| 209 |
"properties": {p["name"]: p["schema"] for p in params}, |
| 210 |
} |
| 211 |
required = [p["name"] for p in params if p["required"]] |
| 212 |
if required: |
| 213 |
flattened["required"] = required |
| 214 |
return flattened |
| 215 |
|
| 216 |
def _create_schema_from_model( |
| 217 |
self, |
| 218 |
model: TModel, |
| 219 |
by_alias: bool = True, |
| 220 |
remove_level: bool = True, |
| 221 |
mode: JsonSchemaMode = "validation", |
| 222 |
) -> Tuple[DictStrAny, bool]: |
| 223 |
if hasattr(model, "__ninja_flatten_map__"): |
| 224 |
schema = self._flatten_schema(model) |
| 225 |
else: |
| 226 |
schema = model.model_json_schema( |
| 227 |
ref_template=REF_TEMPLATE, |
| 228 |
by_alias=by_alias, |
| 229 |
schema_generator=NinjaGenerateJsonSchema, |
| 230 |
mode=mode, |
| 231 |
).copy() |
| 232 |
|
| 233 |
|
| 234 |
if schema.get("$defs"): |
| 235 |
self.add_schema_definitions(schema.pop("$defs")) |
| 236 |
|
| 237 |
if remove_level and len(schema["properties"]) == 1: |
| 238 |
name, details = list(schema["properties"].items())[0] |
| 239 |
|
| 240 |
|
| 241 |
required = name in schema.get("required", {}) |
| 242 |
return details, required |
| 243 |
else: |
| 244 |
return schema, True |
| 245 |
|
| 246 |
def _create_multipart_schema_from_models( |
| 247 |
self, |
| 248 |
models: TModels, |
| 249 |
mode: JsonSchemaMode = "validation", |
| 250 |
) -> Tuple[DictStrAny, str]: |
| 251 |
|
| 252 |
content_type = BODY_CONTENT_TYPES["file"] |
| 253 |
|
| 254 |
|
| 255 |
result = merge_schemas([ |
| 256 |
self._create_schema_from_model(model, remove_level=False)[0] |
| 257 |
for model in models |
| 258 |
]) |
| 259 |
result["title"] = "MultiPartBodyParams" |
| 260 |
|
| 261 |
return result, content_type |
| 262 |
|
| 263 |
def request_body(self, operation: Operation) -> DictStrAny: |
| 264 |
models = [ |
| 265 |
m |
| 266 |
for m in operation.models |
| 267 |
if m.__ninja_param_source__ in BODY_CONTENT_TYPES |
| 268 |
] |
| 269 |
if not models: |
| 270 |
return {} |
| 271 |
|
| 272 |
if len(models) == 1: |
| 273 |
model = models[0] |
| 274 |
content_type = BODY_CONTENT_TYPES[model.__ninja_param_source__] |
| 275 |
schema, required = self._create_schema_from_model( |
| 276 |
model, |
| 277 |
remove_level=model.__ninja_param_source__ == "body", |
| 278 |
mode="validation", |
| 279 |
) |
| 280 |
else: |
| 281 |
schema, content_type = self._create_multipart_schema_from_models( |
| 282 |
models, mode="validation" |
| 283 |
) |
| 284 |
required = True |
| 285 |
|
| 286 |
return { |
| 287 |
"content": {content_type: {"schema": schema}}, |
| 288 |
"required": required, |
| 289 |
} |
| 290 |
|
| 291 |
def responses(self, operation: Operation) -> Dict[int, DictStrAny]: |
| 292 |
assert bool(operation.response_models), f"{operation.response_models} empty" |
| 293 |
|
| 294 |
result = {} |
| 295 |
for status, model in operation.response_models.items(): |
| 296 |
if status == Ellipsis: |
| 297 |
continue |
| 298 |
|
| 299 |
description = responses.get(status, "Unknown Status Code") |
| 300 |
details: Dict[int, Any] = {status: {"description": description}} |
| 301 |
if model not in [None, NOT_SET]: |
| 302 |
|
| 303 |
schema = self._create_schema_from_model( |
| 304 |
model, by_alias=operation.by_alias, mode="serialization" |
| 305 |
)[0] |
| 306 |
if operation.stream_format is not None: |
| 307 |
details[status]["content"] = ( |
| 308 |
operation.stream_format.openapi_content_schema(schema) |
| 309 |
) |
| 310 |
else: |
| 311 |
details[status]["content"] = { |
| 312 |
self.api.renderer.media_type: {"schema": schema} |
| 313 |
} |
| 314 |
result.update(details) |
| 315 |
|
| 316 |
return result |
| 317 |
|
| 318 |
def operation_security(self, operation: Operation) -> Optional[List[DictStrAny]]: |
| 319 |
if not operation.auth_callbacks: |
| 320 |
return None |
| 321 |
result = [] |
| 322 |
for auth in operation.auth_callbacks: |
| 323 |
if hasattr(auth, "openapi_security_schema"): |
| 324 |
scopes: List[DictStrAny] = [] |
| 325 |
name = auth.__class__.__name__ |
| 326 |
result.append({name: scopes}) |
| 327 |
self.securitySchemes[name] = auth.openapi_security_schema |
| 328 |
return result |
| 329 |
|
| 330 |
def get_components(self) -> DictStrAny: |
| 331 |
result = {"schemas": self.schemas} |
| 332 |
if self.securitySchemes: |
| 333 |
result["securitySchemes"] = self.securitySchemes |
| 334 |
return result |
| 335 |
|
| 336 |
def add_schema_definitions(self, definitions: dict) -> None: |
| 337 |
|
| 338 |
|
| 339 |
|
| 340 |
|
| 341 |
|
| 342 |
self.schemas.update(definitions) |
| 343 |
|
| 344 |
|
| 345 |
def flatten_properties( |
| 346 |
prop_name: str, |
| 347 |
prop_details: DictStrAny, |
| 348 |
prop_required: bool, |
| 349 |
definitions: DictStrAny, |
| 350 |
) -> Generator[Tuple[str, DictStrAny, bool], None, None]: |
| 351 |
""" |
| 352 |
extracts all nested model's properties into flat properties |
| 353 |
(used f.e. in GET params with multiple arguments and models) |
| 354 |
""" |
| 355 |
if "allOf" in prop_details: |
| 356 |
resolve_allOf(prop_details, definitions) |
| 357 |
if len(prop_details["allOf"]) == 1 and "enum" in prop_details["allOf"][0]: |
| 358 |
|
| 359 |
yield prop_name, prop_details, prop_required |
| 360 |
else: |
| 361 |
|
| 362 |
for item in prop_details["allOf"]: |
| 363 |
yield from flatten_properties("", item, True, definitions) |
| 364 |
|
| 365 |
elif "items" in prop_details and "$ref" in prop_details["items"]: |
| 366 |
def_name = prop_details["items"]["$ref"].rsplit("/", 1)[-1] |
| 367 |
prop_details["items"].update(definitions[def_name]) |
| 368 |
del prop_details["items"]["$ref"] |
| 369 |
yield prop_name, prop_details, prop_required |
| 370 |
|
| 371 |
elif "$ref" in prop_details: |
| 372 |
def_name = prop_details["$ref"].split("/")[-1] |
| 373 |
definition = definitions[def_name] |
| 374 |
yield from flatten_properties(prop_name, definition, prop_required, definitions) |
| 375 |
|
| 376 |
elif "properties" in prop_details: |
| 377 |
required = set(prop_details.get("required", [])) |
| 378 |
for k, v in prop_details["properties"].items(): |
| 379 |
is_required = k in required |
| 380 |
yield from flatten_properties(k, v, is_required, definitions) |
| 381 |
else: |
| 382 |
yield prop_name, prop_details, prop_required |
| 383 |
|
| 384 |
|
| 385 |
def resolve_allOf(details: DictStrAny, definitions: DictStrAny) -> None: |
| 386 |
""" |
| 387 |
resolves all $ref's in 'allOf' section |
| 388 |
""" |
| 389 |
for item in details["allOf"]: |
| 390 |
if "$ref" in item: |
| 391 |
def_name = item["$ref"].rsplit("/", 1)[-1] |
| 392 |
item.update(definitions[def_name]) |
| 393 |
del item["$ref"] |
| 394 |
|
| 395 |
|
| 396 |
def merge_schemas(schemas: List[DictStrAny]) -> DictStrAny: |
| 397 |
result = schemas[0] |
| 398 |
for scm in schemas[1:]: |
| 399 |
result["properties"].update(scm["properties"]) |
| 400 |
|
| 401 |
required_list = result.get("required", []) |
| 402 |
required_list.extend( |
| 403 |
itertools.chain.from_iterable( |
| 404 |
schema.get("required", ()) for schema in schemas[1:] |
| 405 |
) |
| 406 |
) |
| 407 |
if required_list: |
| 408 |
result["required"] = required_list |
| 409 |
return result |