mirror of https://github.com/tiangolo/fastapi.git
Fix handling router prefix
This commit is contained in:
parent
704d3adb36
commit
d0950a2cbc
|
|
@ -1003,7 +1003,7 @@ class APIRouter(routing.Router):
|
|||
raise FastAPIError(
|
||||
"APIRouter does not support mounting ASGI applications other than StaticFiles."
|
||||
)
|
||||
self._mount(path=path, app=app, name=name)
|
||||
self._mount(path=self.prefix + path, app=app, name=name)
|
||||
|
||||
def _mount(self, path: str, app: ASGIApp, name: str | None = None) -> None:
|
||||
super().mount(path=path, app=app, name=name)
|
||||
|
|
|
|||
|
|
@ -8,18 +8,33 @@ from fastapi.testclient import TestClient
|
|||
|
||||
|
||||
@pytest.mark.parametrize("root_path", ["", "/v1"])
|
||||
def test_mount_static_files_to_apirouter(tmp_path: Path, root_path: str):
|
||||
@pytest.mark.parametrize(
|
||||
("router_prefix", "include_prefix", "request_prefix"),
|
||||
[
|
||||
("", "", ""),
|
||||
("/router", "", "/router"),
|
||||
("", "/router_1", "/router_1"),
|
||||
("/router", "/router_1", "/router_1/router"),
|
||||
],
|
||||
)
|
||||
def test_mount_static_files_to_apirouter(
|
||||
tmp_path: Path,
|
||||
root_path: str,
|
||||
router_prefix: str,
|
||||
include_prefix: str,
|
||||
request_prefix: str,
|
||||
):
|
||||
static_asset = tmp_path / "index.html"
|
||||
static_asset.write_text("Hello, World!")
|
||||
|
||||
router = APIRouter()
|
||||
router = APIRouter(prefix=router_prefix)
|
||||
router.mount("/static", StaticFiles(directory=tmp_path), name="static")
|
||||
|
||||
app = FastAPI(root_path=root_path or None)
|
||||
app.include_router(router)
|
||||
app.include_router(router, prefix=include_prefix)
|
||||
|
||||
client = TestClient(app)
|
||||
response = client.get(f"{root_path}/static/index.html")
|
||||
response = client.get(f"{root_path}{request_prefix}/static/index.html")
|
||||
assert response.status_code == 200
|
||||
assert response.text == "Hello, World!"
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue