Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support import string in router.add_router #1256

Merged
merged 2 commits into from
Aug 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading