From d5588de93c0aa37a70c37f8dd917cdf2ead13e85 Mon Sep 17 00:00:00 2001 From: bilalAlpaslan Date: Sun, 11 Sep 2022 12:37:21 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Fix=20mount=20subapp=20with=20AP?= =?UTF-8?q?Irouter?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/routing.py | 8 +++++ tests/test_mount_app.py | 67 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 tests/test_mount_app.py diff --git a/fastapi/routing.py b/fastapi/routing.py index 6f1a8e9000..b8ecd93dbc 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -778,11 +778,19 @@ class APIRouter(routing.Router): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) + elif isinstance(route, routing.Mount): + self.mount(prefix + route.path, route.app, name=route.name) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) + def mount(self, path: str, app: ASGIApp, name: Optional[str] = None) -> None: + route = routing.Mount(path, app=app, name=name) + if route.__getattribute__("path") == "": + route.__setattr__("path", "/") + self.routes.append(route) + def get( self, path: str, diff --git a/tests/test_mount_app.py b/tests/test_mount_app.py new file mode 100644 index 0000000000..dba5735643 --- /dev/null +++ b/tests/test_mount_app.py @@ -0,0 +1,67 @@ +from fastapi import APIRouter, FastAPI +from fastapi.testclient import TestClient + +app = FastAPI() +app2 = FastAPI() +app3 = FastAPI() +app4 = FastAPI() + + +@app.get("/a") +async def a(): + return "a" + + +@app2.get("/b") +async def b(): + return "b" + + +app.mount("/2", app2) + + +@app3.get("/c") +def c(): + return "c" + + +router = APIRouter() +router.mount("/3", app3) +app.include_router(router) + + +@app4.get("/") +def d(): + return "d" + + +router2 = APIRouter() +router2.mount("/", app4) +app.include_router(router2) + +client = TestClient(app) + + +def test_a(): + response = client.get("/a") + assert response.status_code == 200, response.text + assert response.json() == "a" + + +def test_b(): + response = client.get("/2/b") + assert response.status_code == 200, response.text + assert response.json() == "b" + + +def test_c(): + response = client.get("/3/c") + assert response.status_code == 200, response.text + assert response.json() == "c" + + +def test_mount(): + response = client.get("/") + assert response.status_code == 200, response.text + assert response.json() == "d" + assert router2.routes[0].path == "/"