Debian Codegraph @

ninja/router.py

raw symbols SCIP
1 import re
2 from dataclasses import dataclass, field
3 from typing import (
4 TYPE_CHECKING,
5 Any,
6 Callable,
7 Dict,
8 Iterator,
9 List,
10 Optional,
11 Tuple,
12 Union,
13 )
14
15 from django.urls import URLPattern
16 from django.urls import path as django_path
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 ConfigError
22 from ninja.operation import PathView
23 from ninja.throttling import BaseThrottle
24 from ninja.types import TCallable
25 from ninja.utils import normalize_path, replace_path_param_notation
26
27 if TYPE_CHECKING:
28 from ninja import NinjaAPI # pragma: no cover
29
30
31 __all__ = ["Router", "RouterMount", "BoundRouter"]
32
33
34 @dataclass
35 class RouterMount:
36 """
37 Configuration for how a Router template is mounted to an API.
38
39 This class stores the mount-time configuration without mutating the
40 original Router template, enabling router reuse across multiple APIs
41 or multiple mount points within the same API.
42 """
43
44 template: "Router"
45 prefix: str
46 url_name_prefix: Optional[str] = None
47 auth: Any = NOT_SET
48 throttle: Any = NOT_SET
49 tags: Optional[List[str]] = None
50 inherited_decorators: List[Tuple[Callable, DecoratorMode]] = field(
51 default_factory=list
52 )
53 # Inherited auth/throttle/tags from parent routers (for nested router inheritance)
54 inherited_auth: Any = NOT_SET
55 inherited_throttle: Any = NOT_SET
56 inherited_tags: Optional[List[str]] = None
57
58
59 class BoundRouter:
60 """
61 A Router template bound to a specific API instance.
62
63 Contains cloned operations with decorators applied. Each mount of a router
64 creates a new BoundRouter instance, ensuring complete isolation between mounts.
65 """
66
67 def __init__(self, mount: RouterMount, api: "NinjaAPI") -> None:
68 self.mount = mount
69 self.template = mount.template
70 self.api = api
71 self.prefix = mount.prefix
72 self.url_name_prefix = mount.url_name_prefix
73
74 # Effective settings priority:
75 # 1. mount override (from api.add_router auth/throttle/tags params on this specific mount)
76 # 2. template's own settings (set on the Router itself)
77 # 3. inherited from parent (for nested routers where parent has auth)
78 if mount.auth is not NOT_SET:
79 self.auth = mount.auth
80 elif mount.template.auth is not NOT_SET:
81 self.auth = mount.template.auth
82 elif mount.inherited_auth is not NOT_SET:
83 self.auth = mount.inherited_auth
84 else:
85 self.auth = NOT_SET
86
87 if mount.throttle is not NOT_SET:
88 self.throttle = mount.throttle
89 elif mount.template.throttle is not NOT_SET:
90 self.throttle = mount.template.throttle
91 elif mount.inherited_throttle is not NOT_SET:
92 self.throttle = mount.inherited_throttle
93 else:
94 self.throttle = NOT_SET
95
96 # Tags handling (issue #794):
97 # - mount.tags (from add_router call) = explicit override, use as-is
98 # - Otherwise, accumulate: inherited tags + template's own tags
99 self.tags: Optional[List[str]]
100 if mount.tags is not None:
101 # Explicit tags from add_router() call - use as override
102 self.tags = mount.tags
103 else:
104 # Accumulate inherited tags with template's own tags
105 accumulated_tags: List[str] = []
106 if mount.inherited_tags is not None:
107 accumulated_tags.extend(mount.inherited_tags)
108 if mount.template.tags is not None:
109 accumulated_tags.extend(mount.template.tags)
110 self.tags = accumulated_tags or None
111
112 # Clone operations and apply decorators
113 self.path_operations: Dict[str, PathView] = {}
114 self._bind_operations()
115
116 def _bind_operations(self) -> None:
117 """Clone operations from template and apply effective settings."""
118 effective_decorators = (
119 self.mount.inherited_decorators + self.template._decorators
120 )
121
122 for path, path_view in self.template.path_operations.items():
123 cloned_view = path_view.clone()
124
125 for operation in cloned_view.operations:
126 # Bind to API
127 operation.api = self.api
128
129 # Apply auth inheritance
130 if operation.auth_param == NOT_SET:
131 if self.auth != NOT_SET:
132 operation._set_auth(self.auth)
133 elif self.api.auth != NOT_SET:
134 operation._set_auth(self.api.auth)
135
136 # Apply throttle inheritance
137 if operation.throttle_param == NOT_SET:
138 if self.api.throttle != NOT_SET:
139 throttle = self.api.throttle
140 operation.throttle_objects = (
141 isinstance(throttle, BaseThrottle)
142 and [throttle]
143 or throttle # type: ignore
144 )
145 if self.throttle != NOT_SET:
146 throttle = self.throttle
147 operation.throttle_objects = (
148 isinstance(throttle, BaseThrottle)
149 and [throttle]
150 or throttle # type: ignore
151 )
152
153 # Apply tags inheritance
154 if operation.tags is None and self.tags is not None: # type: ignore[has-type]
155 operation.tags = self.tags # type: ignore[has-type]
156
157 # Apply decorators (fresh application - no tracking needed)
158 for decorator, mode in effective_decorators:
159 if mode == "view":
160 operation.run = decorator(operation.run) # type: ignore
161 elif mode == "operation":
162 operation.view_func = decorator(operation.view_func)
163 else:
164 raise ValueError(
165 f"Invalid decorator mode: {mode}"
166 ) # pragma: no cover
167
168 self.path_operations[path] = cloned_view
169
170 def urls_paths(self, prefix: str) -> Iterator[URLPattern]:
171 """Generate URL patterns for this bound router."""
172 prefix = replace_path_param_notation(prefix)
173 for path, path_view in self.path_operations.items():
174 path = replace_path_param_notation(path)
175 route = "/".join([i for i in (prefix, path) if i])
176 route = normalize_path(route)
177 route = route.lstrip("/")
178
179 for operation in path_view.operations:
180 url_name = getattr(operation, "url_name", "")
181 if not url_name:
182 url_name = self.api.get_operation_url_name(
183 operation, router=self.template
184 )
185 # Apply url_name_prefix if specified
186 if self.url_name_prefix and url_name:
187 url_name = f"{self.url_name_prefix}_{url_name}"
188
189 yield django_path(route, path_view.get_view(), name=url_name)
190
191
192 class Router:
193 def __init__(
194 self,
195 *,
196 auth: Any = NOT_SET,
197 throttle: Union[BaseThrottle, List[BaseThrottle], NOT_SET_TYPE] = NOT_SET,
198 tags: Optional[List[str]] = None,
199 by_alias: Optional[bool] = None,
200 exclude_unset: Optional[bool] = None,
201 exclude_defaults: Optional[bool] = None,
202 exclude_none: Optional[bool] = None,
203 ) -> None:
204 self._frozen = False
205 self.auth = auth
206 self.throttle = throttle
207 self.tags = tags
208 self.by_alias = by_alias
209 self.exclude_unset = exclude_unset
210 self.exclude_defaults = exclude_defaults
211 self.exclude_none = exclude_none
212
213 self.path_operations: Dict[str, PathView] = {}
214 self._routers: List[Tuple[str, Router, Optional[List[str]]]] = []
215 self._decorators: List[Tuple[Callable, DecoratorMode]] = []
216
217 def _freeze(self) -> None:
218 """Mark router as frozen - no more modifications allowed."""
219 self._frozen = True
220 for _, child_router, _ in self._routers:
221 child_router._freeze()
222
223 def _check_not_frozen(self) -> None:
224 """Raise error if attempting to modify a frozen router."""
225 if self._frozen:
226 raise ConfigError(
227 "Cannot modify router after URLs have been generated. "
228 "Routers become frozen when api.urls is accessed."
229 )
230
231 def get(
232 self,
233 path: str,
234 *,
235 auth: Any = NOT_SET,
236 throttle: Union[BaseThrottle, List[BaseThrottle], NOT_SET_TYPE] = NOT_SET,
237 response: Any = NOT_SET,
238 operation_id: Optional[str] = None,
239 summary: Optional[str] = None,
240 description: Optional[str] = None,
241 tags: Optional[List[str]] = None,
242 deprecated: Optional[bool] = None,
243 by_alias: Optional[bool] = None,
244 exclude_unset: Optional[bool] = None,
245 exclude_defaults: Optional[bool] = None,
246 exclude_none: Optional[bool] = None,
247 url_name: Optional[str] = None,
248 include_in_schema: bool = True,
249 openapi_extra: Optional[Dict[str, Any]] = None,
250 ) -> Callable[[TCallable], TCallable]:
251 return self.api_operation(
252 ["GET"],
253 path,
254 auth=auth,
255 throttle=throttle,
256 response=response,
257 operation_id=operation_id,
258 summary=summary,
259 description=description,
260 tags=tags,
261 deprecated=deprecated,
262 by_alias=by_alias,
263 exclude_unset=exclude_unset,
264 exclude_defaults=exclude_defaults,
265 exclude_none=exclude_none,
266 url_name=url_name,
267 include_in_schema=include_in_schema,
268 openapi_extra=openapi_extra,
269 )
270
271 def post(
272 self,
273 path: str,
274 *,
275 auth: Any = NOT_SET,
276 throttle: Union[BaseThrottle, List[BaseThrottle], NOT_SET_TYPE] = NOT_SET,
277 response: Any = NOT_SET,
278 operation_id: Optional[str] = None,
279 summary: Optional[str] = None,
280 description: Optional[str] = None,
281 tags: Optional[List[str]] = None,
282 deprecated: Optional[bool] = None,
283 by_alias: Optional[bool] = None,
284 exclude_unset: Optional[bool] = None,
285 exclude_defaults: Optional[bool] = None,
286 exclude_none: Optional[bool] = None,
287 url_name: Optional[str] = None,
288 include_in_schema: bool = True,
289 openapi_extra: Optional[Dict[str, Any]] = None,
290 ) -> Callable[[TCallable], TCallable]:
291 return self.api_operation(
292 ["POST"],
293 path,
294 auth=auth,
295 throttle=throttle,
296 response=response,
297 operation_id=operation_id,
298 summary=summary,
299 description=description,
300 tags=tags,
301 deprecated=deprecated,
302 by_alias=by_alias,
303 exclude_unset=exclude_unset,
304 exclude_defaults=exclude_defaults,
305 exclude_none=exclude_none,
306 url_name=url_name,
307 include_in_schema=include_in_schema,
308 openapi_extra=openapi_extra,
309 )
310
311 def delete(
312 self,
313 path: str,
314 *,
315 auth: Any = NOT_SET,
316 throttle: Union[BaseThrottle, List[BaseThrottle], NOT_SET_TYPE] = NOT_SET,
317 response: Any = NOT_SET,
318 operation_id: Optional[str] = None,
319 summary: Optional[str] = None,
320 description: Optional[str] = None,
321 tags: Optional[List[str]] = None,
322 deprecated: Optional[bool] = None,
323 by_alias: Optional[bool] = None,
324 exclude_unset: Optional[bool] = None,
325 exclude_defaults: Optional[bool] = None,
326 exclude_none: Optional[bool] = None,
327 url_name: Optional[str] = None,
328 include_in_schema: bool = True,
329 openapi_extra: Optional[Dict[str, Any]] = None,
330 ) -> Callable[[TCallable], TCallable]:
331 return self.api_operation(
332 ["DELETE"],
333 path,
334 auth=auth,
335 throttle=throttle,
336 response=response,
337 operation_id=operation_id,
338 summary=summary,
339 description=description,
340 tags=tags,
341 deprecated=deprecated,
342 by_alias=by_alias,
343 exclude_unset=exclude_unset,
344 exclude_defaults=exclude_defaults,
345 exclude_none=exclude_none,
346 url_name=url_name,
347 include_in_schema=include_in_schema,
348 openapi_extra=openapi_extra,
349 )
350
351 def patch(
352 self,
353 path: str,
354 *,
355 auth: Any = NOT_SET,
356 throttle: Union[BaseThrottle, List[BaseThrottle], NOT_SET_TYPE] = NOT_SET,
357 response: Any = NOT_SET,
358 operation_id: Optional[str] = None,
359 summary: Optional[str] = None,
360 description: Optional[str] = None,
361 tags: Optional[List[str]] = None,
362 deprecated: Optional[bool] = None,
363 by_alias: Optional[bool] = None,
364 exclude_unset: Optional[bool] = None,
365 exclude_defaults: Optional[bool] = None,
366 exclude_none: Optional[bool] = None,
367 url_name: Optional[str] = None,
368 include_in_schema: bool = True,
369 openapi_extra: Optional[Dict[str, Any]] = None,
370 ) -> Callable[[TCallable], TCallable]:
371 return self.api_operation(
372 ["PATCH"],
373 path,
374 auth=auth,
375 throttle=throttle,
376 response=response,
377 operation_id=operation_id,
378 summary=summary,
379 description=description,
380 tags=tags,
381 deprecated=deprecated,
382 by_alias=by_alias,
383 exclude_unset=exclude_unset,
384 exclude_defaults=exclude_defaults,
385 exclude_none=exclude_none,
386 url_name=url_name,
387 include_in_schema=include_in_schema,
388 openapi_extra=openapi_extra,
389 )
390
391 def put(
392 self,
393 path: str,
394 *,
395 auth: Any = NOT_SET,
396 throttle: Union[BaseThrottle, List[BaseThrottle], NOT_SET_TYPE] = NOT_SET,
397 response: Any = NOT_SET,
398 operation_id: Optional[str] = None,
399 summary: Optional[str] = None,
400 description: Optional[str] = None,
401 tags: Optional[List[str]] = None,
402 deprecated: Optional[bool] = None,
403 by_alias: Optional[bool] = None,
404 exclude_unset: Optional[bool] = None,
405 exclude_defaults: Optional[bool] = None,
406 exclude_none: Optional[bool] = None,
407 url_name: Optional[str] = None,
408 include_in_schema: bool = True,
409 openapi_extra: Optional[Dict[str, Any]] = None,
410 ) -> Callable[[TCallable], TCallable]:
411 return self.api_operation(
412 ["PUT"],
413 path,
414 auth=auth,
415 throttle=throttle,
416 response=response,
417 operation_id=operation_id,
418 summary=summary,
419 description=description,
420 tags=tags,
421 deprecated=deprecated,
422 by_alias=by_alias,
423 exclude_unset=exclude_unset,
424 exclude_defaults=exclude_defaults,
425 exclude_none=exclude_none,
426 url_name=url_name,
427 include_in_schema=include_in_schema,
428 openapi_extra=openapi_extra,
429 )
430
431 def api_operation(
432 self,
433 methods: List[str],
434 path: str,
435 *,
436 auth: Any = NOT_SET,
437 throttle: Union[BaseThrottle, List[BaseThrottle], NOT_SET_TYPE] = NOT_SET,
438 response: Any = NOT_SET,
439 operation_id: Optional[str] = None,
440 summary: Optional[str] = None,
441 description: Optional[str] = None,
442 tags: Optional[List[str]] = None,
443 deprecated: Optional[bool] = None,
444 by_alias: Optional[bool] = None,
445 exclude_unset: Optional[bool] = None,
446 exclude_defaults: Optional[bool] = None,
447 exclude_none: Optional[bool] = None,
448 url_name: Optional[str] = None,
449 include_in_schema: bool = True,
450 openapi_extra: Optional[Dict[str, Any]] = None,
451 ) -> Callable[[TCallable], TCallable]:
452 def decorator(view_func: TCallable) -> TCallable:
453 self.add_api_operation(
454 path,
455 methods,
456 view_func,
457 auth=auth,
458 throttle=throttle,
459 response=response,
460 operation_id=operation_id,
461 summary=summary,
462 description=description,
463 tags=tags,
464 deprecated=deprecated,
465 by_alias=by_alias,
466 exclude_unset=exclude_unset,
467 exclude_defaults=exclude_defaults,
468 exclude_none=exclude_none,
469 url_name=url_name,
470 include_in_schema=include_in_schema,
471 openapi_extra=openapi_extra,
472 )
473 return view_func
474
475 return decorator
476
477 def add_api_operation(
478 self,
479 path: str,
480 methods: List[str],
481 view_func: Callable,
482 *,
483 auth: Any = NOT_SET,
484 throttle: Union[BaseThrottle, List[BaseThrottle], NOT_SET_TYPE] = NOT_SET,
485 response: Any = NOT_SET,
486 operation_id: Optional[str] = None,
487 summary: Optional[str] = None,
488 description: Optional[str] = None,
489 tags: Optional[List[str]] = None,
490 deprecated: Optional[bool] = None,
491 by_alias: Optional[bool] = None,
492 exclude_unset: Optional[bool] = None,
493 exclude_defaults: Optional[bool] = None,
494 exclude_none: Optional[bool] = None,
495 url_name: Optional[str] = None,
496 include_in_schema: bool = True,
497 openapi_extra: Optional[Dict[str, Any]] = None,
498 ) -> None:
499 self._check_not_frozen()
500 path = re.sub(r"\{uuid:(\w+)\}", r"{uuidstr:\1}", path, flags=re.IGNORECASE)
501 # django by default convert strings to UUIDs
502 # but we want to keep them as strings to let pydantic handle conversion/validation
503 # if user whants UUID object
504 # uuidstr is custom registered converter
505
506 # No decoration here - will be done in build_routers
507
508 if path not in self.path_operations:
509 path_view = PathView()
510 self.path_operations[path] = path_view
511 else:
512 path_view = self.path_operations[path]
513
514 by_alias = by_alias is None and self.by_alias or by_alias
515 exclude_unset = exclude_unset is None and self.exclude_unset or exclude_unset
516 exclude_defaults = (
517 exclude_defaults is None and self.exclude_defaults or exclude_defaults
518 )
519 exclude_none = exclude_none is None and self.exclude_none or exclude_none
520
521 path_view.add_operation(
522 path=path,
523 methods=methods,
524 view_func=view_func,
525 auth=auth,
526 throttle=throttle,
527 response=response,
528 operation_id=operation_id,
529 summary=summary,
530 description=description,
531 tags=tags,
532 deprecated=deprecated,
533 by_alias=by_alias,
534 exclude_unset=exclude_unset,
535 exclude_defaults=exclude_defaults,
536 exclude_none=exclude_none,
537 url_name=url_name,
538 include_in_schema=include_in_schema,
539 openapi_extra=openapi_extra,
540 )
541 # Note: API binding is now done via BoundRouter when urls are generated
542
543 return None
544
545 def urls_paths(
546 self, prefix: str, api: Optional["NinjaAPI"] = None
547 ) -> Iterator[URLPattern]:
548 """
549 Generate URL patterns for this router.
550
551 Note: This method is primarily for internal use. For mounting routers to APIs,
552 use NinjaAPI.add_router() which handles proper binding via BoundRouter.
553
554 Args:
555 prefix: URL prefix for all paths
556 api: Optional API instance for generating URL names (for backward compat)
557 """
558 # Ensure decorators are applied before generating URLs
559 self._apply_decorators_to_operations()
560
561 prefix = replace_path_param_notation(prefix)
562 for path, path_view in self.path_operations.items():
563 for operation in path_view.operations:
564 path = replace_path_param_notation(path)
565 route = "/".join([i for i in (prefix, path) if i])
566 # to skip lot of checks we simply treat double slash as a mistake:
567 route = normalize_path(route)
568 route = route.lstrip("/")
569
570 url_name = getattr(operation, "url_name", "")
571 if not url_name and api:
572 url_name = api.get_operation_url_name(operation, router=self)
573
574 yield django_path(route, path_view.get_view(), name=url_name)
575
576 def add_router(
577 self,
578 prefix: str,
579 router: Union["Router", str],
580 *,
581 auth: Any = NOT_SET,
582 throttle: Union[BaseThrottle, List[BaseThrottle], NOT_SET_TYPE] = NOT_SET,
583 tags: Optional[List[str]] = None,
584 ) -> None:
585 self._check_not_frozen()
586
587 if isinstance(router, str):
588 router = import_string(router)
589 assert isinstance(router, Router)
590
591 # Store child router with its mount-time configuration
592 # Auth/throttle are stored on the child router template,
593 # but tags from add_router are stored separately to distinguish from Router(tags=...)
594 if auth != NOT_SET:
595 router.auth = auth
596 if throttle != NOT_SET:
597 router.throttle = throttle
598 # Store as (prefix, router, tags) - tags here are mount-level overrides
599 self._routers.append((prefix, router, tags))
600
601 def add_decorator(
602 self,
603 decorator: Callable,
604 mode: DecoratorMode = "operation",
605 ) -> None:
606 """
607 Add a decorator to be applied to all operations in this router.
608
609 Args:
610 decorator: The decorator function to apply
611 mode: "operation" (default) applies after validation,
612 "view" applies before validation
613 """
614 self._check_not_frozen()
615 if mode not in ("view", "operation"):
616 raise ValueError(f"Invalid decorator mode: {mode}")
617 self._decorators.append((decorator, mode))
618
619 def build_routers(
620 self,
621 prefix: str,
622 inherited_decorators: Optional[List[Tuple[Callable, DecoratorMode]]] = None,
623 inherited_auth: Any = NOT_SET,
624 inherited_throttle: Any = NOT_SET,
625 inherited_tags: Optional[List[str]] = None,
626 ) -> List[RouterMount]:
627 """
628 Build mount configurations for this router and all child routers.
629
630 This method does NOT mutate any router state - it returns a list of
631 RouterMount objects that describe how to bind routers to an API.
632
633 Args:
634 prefix: The URL prefix for this router
635 inherited_decorators: Decorators inherited from parent routers/API
636 inherited_auth: Auth inherited from parent routers
637 inherited_throttle: Throttle inherited from parent routers
638 inherited_tags: Tags inherited from parent routers
639
640 Returns:
641 List of RouterMount configurations for this router and all descendants
642 """
643 if inherited_decorators is None:
644 inherited_decorators = []
645
646 # Create mount configuration for this router
647 mount = RouterMount(
648 template=self,
649 prefix=prefix,
650 inherited_decorators=list(inherited_decorators),
651 inherited_auth=inherited_auth,
652 inherited_throttle=inherited_throttle,
653 inherited_tags=inherited_tags,
654 )
655
656 # Calculate values to pass to children
657 child_decorators = inherited_decorators + self._decorators
658
659 # For auth/throttle/tags, effective value is used for children:
660 # priority: this router's own setting > inherited
661 child_auth = self.auth if self.auth is not NOT_SET else inherited_auth
662 child_throttle = (
663 self.throttle if self.throttle is not NOT_SET else inherited_throttle
664 )
665 child_tags = self.tags if self.tags is not None else inherited_tags
666
667 # Build mounts for child routers
668 child_mounts: List[RouterMount] = []
669 for child_prefix, child_router, child_mount_tags in self._routers:
670 child_path = normalize_path("/".join((prefix, child_prefix))).lstrip("/")
671 mounts = child_router.build_routers(
672 child_path,
673 child_decorators,
674 child_auth,
675 child_throttle,
676 child_tags,
677 )
678 # Apply mount-level tags override to the first mount (the child router itself)
679 if mounts and child_mount_tags is not None:
680 mounts[0].tags = child_mount_tags
681 child_mounts.extend(mounts)
682
683 return [mount, *child_mounts]
684
685 def _apply_decorators_to_operations(self) -> None:
686 """Apply all stored decorators to operations in this router"""
687 for path_view in self.path_operations.values():
688 for operation in path_view.operations:
689 # Track what decorators have already been applied to avoid duplicates
690 applied_decorators = getattr(operation, "_applied_decorators", [])
691
692 # Apply decorators that haven't been applied yet
693 for decorator, mode in self._decorators:
694 if (decorator, mode) not in applied_decorators:
695 if mode == "view":
696 operation.run = decorator(operation.run) # type: ignore
697 elif mode == "operation":
698 operation.view_func = decorator(operation.view_func)
699 else:
700 raise ValueError(
701 f"Invalid decorator mode: {mode}"
702 ) # pragma: no cover
703 applied_decorators.append((decorator, mode))
704
705 # Store what decorators have been applied
706 operation._applied_decorators = applied_decorators # type: ignore[attr-defined]