🐛 Fix mount subapp with APIrouter

This commit is contained in:
bilalAlpaslan 2022-09-11 12:37:21 +03:00
parent 5c576e42be
commit d5588de93c
2 changed files with 75 additions and 0 deletions

View File

@ -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,

67
tests/test_mount_app.py Normal file
View File

@ -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 == "/"