From bf21aec6758d96420aad12c38531aad42db72eef Mon Sep 17 00:00:00 2001 From: Martin Svoboda Date: Mon, 5 Aug 2024 16:49:15 +0200 Subject: [PATCH 1/2] Support router.add_router with import string --- ninja/router.py | 7 ++++++- tests/test_router_add_router.py | 22 ++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 tests/test_router_add_router.py diff --git a/ninja/router.py b/ninja/router.py index c1d1372a..13e26d41 100644 --- a/ninja/router.py +++ b/ninja/router.py @@ -12,6 +12,7 @@ from django.urls import URLPattern from django.urls import path as django_path +from django.utils.module_loading import import_string from ninja.constants import NOT_SET, NOT_SET_TYPE from ninja.errors import ConfigError @@ -371,12 +372,16 @@ def urls_paths(self, prefix: str) -> Iterator[URLPattern]: def add_router( self, prefix: str, - router: "Router", + router: Union["Router", str], *, auth: Any = NOT_SET, throttle: Union[BaseThrottle, List[BaseThrottle], NOT_SET_TYPE] = NOT_SET, tags: Optional[List[str]] = None, ) -> None: + if isinstance(router, str): + router = import_string(router) + assert isinstance(router, Router) + if self.api: # we are already attached to an api self.api.add_router( diff --git a/tests/test_router_add_router.py b/tests/test_router_add_router.py new file mode 100644 index 00000000..545c9e23 --- /dev/null +++ b/tests/test_router_add_router.py @@ -0,0 +1,22 @@ +from ninja import NinjaAPI, Router +from ninja.testing import TestClient + + +router = Router() + + +@router.get("/") +def op(request): + return True + + +def test_add_router_with_string_path(): + main_router = Router() + main_router.add_router("sub", "tests.test_router_add_router.router") + + api = NinjaAPI() + api.add_router("main", main_router) + + client = TestClient(api) + + assert client.get("/main/sub/").status_code == 200 From c25b7eb44d63afe295c286dc19ad18b01c57c991 Mon Sep 17 00:00:00 2001 From: Martin Svoboda Date: Mon, 5 Aug 2024 17:15:19 +0200 Subject: [PATCH 2/2] Fix ruff --- tests/test_router_add_router.py | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/test_router_add_router.py b/tests/test_router_add_router.py index 545c9e23..e7778929 100644 --- a/tests/test_router_add_router.py +++ b/tests/test_router_add_router.py @@ -1,7 +1,6 @@ from ninja import NinjaAPI, Router from ninja.testing import TestClient - router = Router()