Debian Codegraph @

ninja/main.py

raw symbols SCIP
1 from typing import (
2 TYPE_CHECKING,
3 Any,
4 Callable,
5 Dict,
6 List,
7 Optional,
8 Sequence,
9 Tuple,
10 Type,
11 TypeVar,
12 Union,
13 )
14
15 from django.http import HttpRequest, HttpResponse
16 from django.urls import URLPattern, URLResolver, reverse
17 from django.utils.module_loading import import_string
18
19 from ninja.constants import NOT_SET, NOT_SET_TYPE
20 from ninja.decorators import DecoratorMode
21 from ninja.errors import (
22 ConfigError,
23 ValidationError,
24 ValidationErrorContext,
25 set_default_exc_handlers,
26 )
27 from ninja.openapi import get_schema
28 from ninja.openapi.docs import DocsBase, Swagger
29 from ninja.openapi.schema import OpenAPISchema
30 from ninja.openapi.urls import get_openapi_urls, get_root_url
31 from ninja.parser import Parser
32 from ninja.renderers import BaseRenderer, JSONRenderer
33 from ninja.router import BoundRouter, Router, RouterMount
34 from ninja.throttling import BaseThrottle
35 from ninja.types import DictStrAny, TCallable
36
37 if TYPE_CHECKING:
38 from .operation import Operation # pragma: no cover
39
40 __all__ = ["NinjaAPI"]
41
42 _E = TypeVar("_E", bound=Exception)
43 Exc = Union[_E, Type[_E]]
44 ExcHandler = Callable[[HttpRequest, Exc[_E]], HttpResponse]
45
46
47 class NinjaAPI:
48 """
49 Ninja API
50 """
51
52 def __init__(
53 self,
54 *,
55 title: str = "NinjaAPI",
56 version: str = "1.0.0",
57 description: str = "",
58 openapi_url: Optional[str] = "/openapi.json",
59 docs: DocsBase = Swagger(),
60 docs_url: Optional[str] = "/docs",
61 docs_decorator: Optional[Callable[[TCallable], TCallable]] = None,
62 servers: Optional[List[DictStrAny]] = None,
63 urls_namespace: Optional[str] = None,
64 auth: Optional[Union[Sequence[Callable], Callable, NOT_SET_TYPE]] = NOT_SET,
65 throttle: Union[BaseThrottle, List[BaseThrottle], NOT_SET_TYPE] = NOT_SET,
66 renderer: Optional[BaseRenderer] = None,
67 parser: Optional[Parser] = None,
68 default_router: Optional[Router] = None,
69 openapi_extra: Optional[Dict[str, Any]] = None,
70 ):
71 """
72 Args:
73 title: A title for the api.
74 description: A description for the api.
75 version: The API version.
76 urls_namespace: The Django URL namespace for the API. If not provided, the namespace will be ``"api-" + self.version``.
77 openapi_url: The relative URL to serve the openAPI spec.
78 openapi_extra: Additional attributes for the openAPI spec.
79 docs_url: The relative URL to serve the API docs.
80 servers: List of target hosts used in openAPI spec.
81 auth (Callable | Sequence[Callable] | NOT_SET | None): Authentication class
82 renderer: Default response renderer
83 parser: Default request parser
84 """
85 self.title = title
86 self.version = version
87 self.description = description
88 self.openapi_url = openapi_url
89 self.docs = docs
90 self.docs_url = docs_url
91 self.docs_decorator = docs_decorator
92 self.servers = servers or []
93 self.urls_namespace = urls_namespace or f"api-{self.version}"
94 self.renderer = renderer or JSONRenderer()
95 self.parser = parser or Parser()
96 self.openapi_extra = openapi_extra or {}
97
98 self._exception_handlers: Dict[Exc, ExcHandler] = {}
99 self.set_default_exception_handlers()
100
101 self.auth: Optional[Union[Sequence[Callable], NOT_SET_TYPE]]
102
103 if callable(auth):
104 self.auth = [auth]
105 else:
106 self.auth = auth
107
108 self.throttle = throttle
109
110 # Top-level router registrations (new architecture)
111 # Stores (prefix, router, auth, throttle, tags, url_name_prefix) for each add_router call
112 self._router_registrations: List[
113 Tuple[str, Router, Any, Any, Optional[List[str]], Optional[str]]
114 ] = []
115 self._bound_routers_cache: Optional[List[BoundRouter]] = None
116
117 # Backward compat: keep _routers list populated
118 self._routers: List[Tuple[str, Router]] = []
119
120 self.default_router = default_router or Router()
121 self.add_router("", self.default_router)
122
123 def get(
124 self,
125 path: str,
126 *,
127 auth: Any = NOT_SET,
128 throttle: Union[BaseThrottle, List[BaseThrottle], NOT_SET_TYPE] = NOT_SET,
129 response: Any = NOT_SET,
130 operation_id: Optional[str] = None,
131 summary: Optional[str] = None,
132 description: Optional[str] = None,
133 tags: Optional[List[str]] = None,
134 deprecated: Optional[bool] = None,
135 by_alias: Optional[bool] = None,
136 exclude_unset: Optional[bool] = None,
137 exclude_defaults: Optional[bool] = None,
138 exclude_none: Optional[bool] = None,
139 url_name: Optional[str] = None,
140 include_in_schema: bool = True,
141 openapi_extra: Optional[Dict[str, Any]] = None,
142 ) -> Callable[[TCallable], TCallable]:
143 """
144 `GET` operation. See <a href="../operations-parameters">operations
145 parameters</a> reference.
146 """
147 return self.default_router.get(
148 path,
149 auth=auth is NOT_SET and self.auth or auth,
150 throttle=throttle is NOT_SET and self.throttle or throttle,
151 response=response,
152 operation_id=operation_id,
153 summary=summary,
154 description=description,
155 tags=tags,
156 deprecated=deprecated,
157 by_alias=by_alias,
158 exclude_unset=exclude_unset,
159 exclude_defaults=exclude_defaults,
160 exclude_none=exclude_none,
161 url_name=url_name,
162 include_in_schema=include_in_schema,
163 openapi_extra=openapi_extra,
164 )
165
166 def post(
167 self,
168 path: str,
169 *,
170 auth: Any = NOT_SET,
171 throttle: Union[BaseThrottle, List[BaseThrottle], NOT_SET_TYPE] = NOT_SET,
172 response: Any = NOT_SET,
173 operation_id: Optional[str] = None,
174 summary: Optional[str] = None,
175 description: Optional[str] = None,
176 tags: Optional[List[str]] = None,
177 deprecated: Optional[bool] = None,
178 by_alias: Optional[bool] = None,
179 exclude_unset: Optional[bool] = None,
180 exclude_defaults: Optional[bool] = None,
181 exclude_none: Optional[bool] = None,
182 url_name: Optional[str] = None,
183 include_in_schema: bool = True,
184 openapi_extra: Optional[Dict[str, Any]] = None,
185 ) -> Callable[[TCallable], TCallable]:
186 """
187 `POST` operation. See <a href="../operations-parameters">operations
188 parameters</a> reference.
189 """
190 return self.default_router.post(
191 path,
192 auth=auth is NOT_SET and self.auth or auth,
193 throttle=throttle is NOT_SET and self.throttle or throttle,
194 response=response,
195 operation_id=operation_id,
196 summary=summary,
197 description=description,
198 tags=tags,
199 deprecated=deprecated,
200 by_alias=by_alias,
201 exclude_unset=exclude_unset,
202 exclude_defaults=exclude_defaults,
203 exclude_none=exclude_none,
204 url_name=url_name,
205 include_in_schema=include_in_schema,
206 openapi_extra=openapi_extra,
207 )
208
209 def delete(
210 self,
211 path: str,
212 *,
213 auth: Any = NOT_SET,
214 throttle: Union[BaseThrottle, List[BaseThrottle], NOT_SET_TYPE] = NOT_SET,
215 response: Any = NOT_SET,
216 operation_id: Optional[str] = None,
217 summary: Optional[str] = None,
218 description: Optional[str] = None,
219 tags: Optional[List[str]] = None,
220 deprecated: Optional[bool] = None,
221 by_alias: Optional[bool] = None,
222 exclude_unset: Optional[bool] = None,
223 exclude_defaults: Optional[bool] = None,
224 exclude_none: Optional[bool] = None,
225 url_name: Optional[str] = None,
226 include_in_schema: bool = True,
227 openapi_extra: Optional[Dict[str, Any]] = None,
228 ) -> Callable[[TCallable], TCallable]:
229 """
230 `DELETE` operation. See <a href="../operations-parameters">operations
231 parameters</a> reference.
232 """
233 return self.default_router.delete(
234 path,
235 auth=auth is NOT_SET and self.auth or auth,
236 throttle=throttle is NOT_SET and self.throttle or throttle,
237 response=response,
238 operation_id=operation_id,
239 summary=summary,
240 description=description,
241 tags=tags,
242 deprecated=deprecated,
243 by_alias=by_alias,
244 exclude_unset=exclude_unset,
245 exclude_defaults=exclude_defaults,
246 exclude_none=exclude_none,
247 url_name=url_name,
248 include_in_schema=include_in_schema,
249 openapi_extra=openapi_extra,
250 )
251
252 def patch(
253 self,
254 path: str,
255 *,
256 auth: Any = NOT_SET,
257 throttle: Union[BaseThrottle, List[BaseThrottle], NOT_SET_TYPE] = NOT_SET,
258 response: Any = NOT_SET,
259 operation_id: Optional[str] = None,
260 summary: Optional[str] = None,
261 description: Optional[str] = None,
262 tags: Optional[List[str]] = None,
263 deprecated: Optional[bool] = None,
264 by_alias: Optional[bool] = None,
265 exclude_unset: Optional[bool] = None,
266 exclude_defaults: Optional[bool] = None,
267 exclude_none: Optional[bool] = None,
268 url_name: Optional[str] = None,
269 include_in_schema: bool = True,
270 openapi_extra: Optional[Dict[str, Any]] = None,
271 ) -> Callable[[TCallable], TCallable]:
272 """
273 `PATCH` operation. See <a href="../operations-parameters">operations
274 parameters</a> reference.
275 """
276 return self.default_router.patch(
277 path,
278 auth=auth is NOT_SET and self.auth or auth,
279 throttle=throttle is NOT_SET and self.throttle or throttle,
280 response=response,
281 operation_id=operation_id,
282 summary=summary,
283 description=description,
284 tags=tags,
285 deprecated=deprecated,
286 by_alias=by_alias,
287 exclude_unset=exclude_unset,
288 exclude_defaults=exclude_defaults,
289 exclude_none=exclude_none,
290 url_name=url_name,
291 include_in_schema=include_in_schema,
292 openapi_extra=openapi_extra,
293 )
294
295 def put(
296 self,
297 path: str,
298 *,
299 auth: Any = NOT_SET,
300 throttle: Union[BaseThrottle, List[BaseThrottle], NOT_SET_TYPE] = NOT_SET,
301 response: Any = NOT_SET,
302 operation_id: Optional[str] = None,
303 summary: Optional[str] = None,
304 description: Optional[str] = None,
305 tags: Optional[List[str]] = None,
306 deprecated: Optional[bool] = None,
307 by_alias: Optional[bool] = None,
308 exclude_unset: Optional[bool] = None,
309 exclude_defaults: Optional[bool] = None,
310 exclude_none: Optional[bool] = None,
311 url_name: Optional[str] = None,
312 include_in_schema: bool = True,
313 openapi_extra: Optional[Dict[str, Any]] = None,
314 ) -> Callable[[TCallable], TCallable]:
315 """
316 `PUT` operation. See <a href="../operations-parameters">operations
317 parameters</a> reference.
318 """
319 return self.default_router.put(
320 path,
321 auth=auth is NOT_SET and self.auth or auth,
322 throttle=throttle is NOT_SET and self.throttle or throttle,
323 response=response,
324 operation_id=operation_id,
325 summary=summary,
326 description=description,
327 tags=tags,
328 deprecated=deprecated,
329 by_alias=by_alias,
330 exclude_unset=exclude_unset,
331 exclude_defaults=exclude_defaults,
332 exclude_none=exclude_none,
333 url_name=url_name,
334 include_in_schema=include_in_schema,
335 openapi_extra=openapi_extra,
336 )
337
338 def api_operation(
339 self,
340 methods: List[str],
341 path: str,
342 *,
343 auth: Any = NOT_SET,
344 throttle: Union[BaseThrottle, List[BaseThrottle], NOT_SET_TYPE] = NOT_SET,
345 response: Any = NOT_SET,
346 operation_id: Optional[str] = None,
347 summary: Optional[str] = None,
348 description: Optional[str] = None,
349 tags: Optional[List[str]] = None,
350 deprecated: Optional[bool] = None,
351 by_alias: Optional[bool] = None,
352 exclude_unset: Optional[bool] = None,
353 exclude_defaults: Optional[bool] = None,
354 exclude_none: Optional[bool] = None,
355 url_name: Optional[str] = None,
356 include_in_schema: bool = True,
357 openapi_extra: Optional[Dict[str, Any]] = None,
358 ) -> Callable[[TCallable], TCallable]:
359 return self.default_router.api_operation(
360 methods,
361 path,
362 auth=auth is NOT_SET and self.auth or auth,
363 throttle=throttle is NOT_SET and self.throttle or throttle,
364 response=response,
365 operation_id=operation_id,
366 summary=summary,
367 description=description,
368 tags=tags,
369 deprecated=deprecated,
370 by_alias=by_alias,
371 exclude_unset=exclude_unset,
372 exclude_defaults=exclude_defaults,
373 exclude_none=exclude_none,
374 url_name=url_name,
375 include_in_schema=include_in_schema,
376 openapi_extra=openapi_extra,
377 )
378
379 def add_decorator(
380 self,
381 decorator: Callable,
382 mode: DecoratorMode = "operation",
383 ) -> None:
384 """
385 Add a decorator to be applied to all operations in the entire API.
386
387 Args:
388 decorator: The decorator function to apply
389 mode: "operation" (default) applies after validation,
390 "view" applies before validation
391 """
392 # Store decorator on default router - will be inherited by all routers during build
393 self.default_router.add_decorator(decorator, mode)
394
395 def add_router(
396 self,
397 prefix: str,
398 router: Union[Router, str],
399 *,
400 auth: Any = NOT_SET,
401 throttle: Union[BaseThrottle, List[BaseThrottle], NOT_SET_TYPE] = NOT_SET,
402 tags: Optional[List[str]] = None,
403 url_name_prefix: Optional[str] = None,
404 parent_router: Optional[Router] = None,
405 ) -> None:
406 """
407 Add a router to this API.
408
409 Args:
410 prefix: URL prefix for all routes in the router
411 router: Router instance or import path string
412 auth: Authentication override for this router
413 throttle: Throttle override for this router
414 tags: Tags override for this router
415 url_name_prefix: Prefix for URL names (required when mounting same router multiple times)
416 parent_router: Internal use - parent router for nested routers
417 """
418 # Prevent adding routers after URLs have been generated
419 if self._bound_routers_cache is not None:
420 raise ConfigError(
421 "Cannot add routers after URLs have been generated. "
422 "Add all routers before accessing api.urls"
423 )
424
425 if isinstance(router, str):
426 router = import_string(router)
427 assert isinstance(router, Router)
428
429 # Check for duplicate router template - require url_name_prefix
430 existing_templates = {reg[1] for reg in self._router_registrations}
431 if router in existing_templates and url_name_prefix is None:
432 raise ConfigError(
433 "Router is already mounted to this API. When mounting the same router "
434 "multiple times, you must provide unique url_name_prefix for each mount."
435 )
436
437 # Store registration for later processing during URL generation
438 # This allows child routers to be added after add_router() is called
439 self._router_registrations.append((
440 prefix,
441 router,
442 auth,
443 throttle,
444 tags,
445 url_name_prefix,
446 ))
447
448 # Backward compat: keep _routers list updated (just the top-level router)
449 self._routers.append((prefix, router))
450
451 @property
452 def urls(self) -> Tuple[List[Union[URLResolver, URLPattern]], str, str]:
453 """
454 str: URL configuration
455
456 Returns:
457
458 Django URL configuration
459 """
460 self._validate()
461 return (
462 self._get_urls(),
463 "ninja",
464 self.urls_namespace.split(":")[-1],
465 # ^ if api included into nested urls, we only care about last bit here
466 )
467
468 def _get_bound_routers(self) -> List[BoundRouter]:
469 """Get or create bound router instances."""
470 if self._bound_routers_cache is None:
471 # Build mounts from registrations (delayed to capture all child routers)
472 all_mounts: List[RouterMount] = []
473
474 for (
475 prefix,
476 router,
477 auth,
478 throttle,
479 tags,
480 url_name_prefix,
481 ) in self._router_registrations:
482 # Get API-level decorators from default router
483 api_decorators = (
484 self.default_router._decorators
485 if router is not self.default_router
486 else []
487 )
488
489 # Build mount configurations (non-mutating)
490 # Pass auth/throttle/tags so they can be inherited by children
491 mounts = router.build_routers(
492 prefix,
493 api_decorators,
494 inherited_auth=auth,
495 inherited_throttle=throttle,
496 inherited_tags=tags,
497 )
498
499 # Apply mount-level overrides to the first (parent) mount
500 # build_routers() always returns at least one mount (the router itself)
501 first_mount = mounts[0]
502 if auth is not NOT_SET:
503 first_mount.auth = auth
504 if throttle is not NOT_SET:
505 first_mount.throttle = throttle
506 if tags is not None:
507 first_mount.tags = tags
508
509 # Apply url_name_prefix to all mounts
510 if url_name_prefix is not None:
511 for mount in mounts:
512 mount.url_name_prefix = url_name_prefix
513
514 all_mounts.extend(mounts)
515
516 # Create bound routers from mounts
517 self._bound_routers_cache = [
518 BoundRouter(mount, self) for mount in all_mounts
519 ]
520
521 # Freeze all templates after binding
522 for mount in all_mounts:
523 mount.template._freeze()
524
525 # Update _routers for backward compat (include all nested routers)
526 self._routers = [(m.prefix, m.template) for m in all_mounts]
527
528 return self._bound_routers_cache
529
530 def _get_urls(self) -> List[Union[URLResolver, URLPattern]]:
531 result = get_openapi_urls(self)
532
533 for bound_router in self._get_bound_routers():
534 result.extend(bound_router.urls_paths(bound_router.prefix))
535
536 result.append(get_root_url(self))
537 return result
538
539 def get_root_path(self, path_params: DictStrAny) -> str:
540 name = f"{self.urls_namespace}:api-root"
541 return reverse(name, kwargs=path_params)
542
543 def create_response(
544 self,
545 request: HttpRequest,
546 data: Any,
547 *,
548 status: Optional[int] = None,
549 temporal_response: Optional[HttpResponse] = None,
550 ) -> HttpResponse:
551 if temporal_response:
552 status = temporal_response.status_code
553 assert status
554
555 content = self.renderer.render(request, data, response_status=status)
556
557 if temporal_response:
558 response = temporal_response
559 response.content = content
560 else:
561 response = HttpResponse(
562 content, status=status, content_type=self.get_content_type()
563 )
564
565 return response
566
567 def create_temporal_response(self, request: HttpRequest) -> HttpResponse:
568 return HttpResponse("", content_type=self.get_content_type())
569
570 def get_content_type(self) -> str:
571 return f"{self.renderer.media_type}; charset={self.renderer.charset}"
572
573 def get_openapi_schema(
574 self,
575 *,
576 path_prefix: Optional[str] = None,
577 path_params: Optional[DictStrAny] = None,
578 ) -> OpenAPISchema:
579 if path_prefix is None:
580 path_prefix = self.get_root_path(path_params or {})
581 return get_schema(api=self, path_prefix=path_prefix)
582
583 def get_openapi_operation_id(self, operation: "Operation") -> str:
584 name = operation.view_func.__name__
585 module = operation.view_func.__module__
586 return (module + "_" + name).replace(".", "_")
587
588 def get_operation_url_name(self, operation: "Operation", router: Router) -> str:
589 """
590 Get the default URL name to use for an operation if it wasn't
591 explicitly provided.
592 """
593 return operation.view_func.__name__
594
595 def add_exception_handler(
596 self, exc_class: Type[_E], handler: ExcHandler[_E]
597 ) -> None:
598 assert issubclass(exc_class, Exception)
599 self._exception_handlers[exc_class] = handler
600
601 def exception_handler(
602 self, exc_class: Type[Exception]
603 ) -> Callable[[TCallable], TCallable]:
604 def decorator(func: TCallable) -> TCallable:
605 self.add_exception_handler(exc_class, func)
606 return func
607
608 return decorator
609
610 def set_default_exception_handlers(self) -> None:
611 set_default_exc_handlers(self)
612
613 def on_exception(self, request: HttpRequest, exc: Exc[_E]) -> HttpResponse:
614 handler = self._lookup_exception_handler(exc)
615 if handler is None:
616 raise exc
617 return handler(request, exc)
618
619 def validation_error_from_error_contexts(
620 self, error_contexts: List[ValidationErrorContext]
621 ) -> ValidationError:
622 errors: List[Dict[str, Any]] = []
623 for context in error_contexts:
624 model = context.model
625 e = context.pydantic_validation_error
626 for i in e.errors(include_url=False):
627 i["loc"] = (
628 model.__ninja_param_source__,
629 ) + model.__ninja_flatten_map_reverse__.get(i["loc"], i["loc"])
630 # removing pydantic hints
631 del i["input"] # type: ignore
632 if (
633 "ctx" in i
634 and "error" in i["ctx"]
635 and isinstance(i["ctx"]["error"], Exception)
636 ):
637 i["ctx"]["error"] = str(i["ctx"]["error"])
638 errors.append(dict(i))
639 return ValidationError(errors)
640
641 def _lookup_exception_handler(self, exc: Exc[_E]) -> Optional[ExcHandler[_E]]:
642 for cls in type(exc).__mro__:
643 if cls in self._exception_handlers:
644 return self._exception_handlers[cls]
645
646 return None
647
648 def _validate(self) -> None:
649 # Registry check no longer needed - routers are independent templates
650 # and can be reused across multiple APIs without conflicts
651 pass