diff --git a/baize/asgi/routing.py b/baize/asgi/routing.py index cb72ab0..125101d 100644 --- a/baize/asgi/routing.py +++ b/baize/asgi/routing.py @@ -20,7 +20,11 @@ class Router(BaseRouter[ASGIApp]): async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: if scope["type"] == "lifespan": # pragma: no cover raise RuntimeError("Unsupported lifespan in `Router`") - result = self.search(scope["path"]) + root_path = scope.get("root_path", "") + path = scope["path"] + if root_path and path.startswith(root_path): + path = path[len(root_path) :] + result = self.search(path) if result is None: response: ASGIApp = Response(404) else: @@ -48,14 +52,16 @@ class Subpaths(BaseSubpaths[ASGIApp]): async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: if scope["type"] == "lifespan": # pragma: no cover raise RuntimeError("Unsupported lifespan in `Subpaths`") + root_path = scope.get("root_path", "") path = scope["path"] + if root_path and path.startswith(root_path): + path = path[len(root_path) :] result = self.search(path) if result is None: response: ASGIApp = Response(404) else: prefix, response = result - scope["root_path"] = scope.get("root_path", "") + prefix - scope["path"] = path[len(prefix) :] + scope["root_path"] = root_path + prefix return await response(scope, receive, send) diff --git a/baize/datastructures.py b/baize/datastructures.py index 4b7c020..d6fdb98 100644 --- a/baize/datastructures.py +++ b/baize/datastructures.py @@ -204,7 +204,7 @@ def __init__( elif scope is not None: scheme = scope.get("scheme", "http") server = scope.get("server", None) - path = scope.get("root_path", "") + scope["path"] + path = scope["path"] query_string = scope.get("query_string", b"") host_header = None diff --git a/tests/test_asgi.py b/tests/test_asgi.py index 019deed..6a051b6 100644 --- a/tests/test_asgi.py +++ b/tests/test_asgi.py @@ -1106,12 +1106,30 @@ async def path(request: Request) -> Response: app=Subpaths( ("/frist", root), ("/latest", path), + ( + "/s", + Subpaths( + ("/frist", root), + ("/latest", path), + ), + ), + ( + "/r", + Router( + ("/frist", root), + ("/latest", path), + ), + ), ), base_url="http://testServer/", ) as client: assert (await client.get("/")).status_code == 404 assert (await client.get("/frist")).text == "/frist" - assert (await client.get("/latest")).text == "" + assert (await client.get("/latest/")).text == "/latest/" + assert (await client.get("/s/frist/")).text == "/s/frist" + assert (await client.get("/s/latest/")).text == "/s/latest/" + assert (await client.get("/r/frist")).text == "/r" + assert (await client.get("/r/latest")).text == "/r/latest" async with httpx.AsyncClient( app=Subpaths(