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: def mount(self, path: str, app: ASGIApp, name: str | None = None) -> None:
""" """
Mount a `StaticFiles` instance at the given path. Mount a StaticFiles instance.
Will raise a FastAPIError exception if app is not an instance of StaticFiles.
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.
""" """
if not isinstance(app, StaticFiles): if not isinstance(app, StaticFiles):
raise FastAPIError( raise FastAPIError(
"APIRouter does not support mounting ASGI applications other than " "APIRouter does not support mounting ASGI applications other than StaticFiles."
"StaticFiles. Mount sub-applications directly on the root FastAPI "
"instance instead."
) )
self._mount(path=path, app=app, name=name) 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( with pytest.raises(
FastAPIError, 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) router.mount("/sub", sub_app)
Loading…
Cancel
Save