Browse Source

fix: support mounting StaticFiles to APIRouter, raise error for other apps

- Override APIRouter.mount() to only allow StaticFiles; raise FastAPIError
  for any other ASGI app with a clear error message
- Add APIRouter._mount() as internal method used by include_router()
  and FastAPI.mount() to bypass the StaticFiles-only restriction
- Override FastAPI.mount() to call self.router._mount() directly
- Propagate StaticFiles mounts in include_router() via _mount()
- Rename test file to test_apirouter_mount.py

Fixes #10180
pull/14924/head
kimchikingdom 5 months ago
parent
commit
a73cf952b0
  1. 12
      fastapi/routing.py
  2. 2
      tests/test_apirouter_mount.py

12
fastapi/routing.py

@ -996,18 +996,12 @@ class APIRouter(routing.Router):
def mount(self, path: str, app: ASGIApp, name: str | None = None) -> None:
"""
Mount a `StaticFiles` instance at the given path.
Raises `FastAPIError` if `app` is not an instance of `StaticFiles`,
since mounting arbitrary ASGI sub-applications under an `APIRouter`
is not supported. Sub-applications should be mounted directly on
the root `FastAPI` instance instead.
Mount a StaticFiles instance.
Will raise a FastAPIError exception if app is not an instance of StaticFiles.
"""
if not isinstance(app, StaticFiles):
raise FastAPIError(
"APIRouter does not support mounting ASGI applications other than "
"StaticFiles. Mount sub-applications directly on the root FastAPI "
"instance instead."
"APIRouter does not support mounting ASGI applications other than StaticFiles."
)
self._mount(path=path, app=app, name=name)

2
tests/test_router_mount.py → tests/test_apirouter_mount.py

@ -76,6 +76,6 @@ def test_mount_non_staticfiles_app_raises_error() -> None:
with pytest.raises(
FastAPIError,
match="APIRouter does not support mounting ASGI applications other than StaticFiles",
match="APIRouter does not support mounting ASGI applications other than StaticFiles.",
):
router.mount("/sub", sub_app)
Loading…
Cancel
Save