Skip to content

Commit

Permalink
Merge pull request #1256 from engine2net/add-router-as-path-string
Browse files Browse the repository at this point in the history
Support import string in router.add_router
  • Loading branch information
vitalik committed Aug 5, 2024
2 parents eecb05f + c25b7eb commit 3c55d99
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
7 changes: 6 additions & 1 deletion ninja/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down
21 changes: 21 additions & 0 deletions tests/test_router_add_router.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
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

0 comments on commit 3c55d99

Please sign in to comment.