mirror of https://github.com/tiangolo/fastapi.git
🐛 Fix mount subapp with APIrouter
This commit is contained in:
parent
5c576e42be
commit
d5588de93c
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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 == "/"
|
||||
Loading…
Reference in New Issue