From c1f2ac00ac72053b598070d90a95b3d705f22791 Mon Sep 17 00:00:00 2001 From: Ethan Zhang <33052368+c0debeez@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:52:03 +0800 Subject: [PATCH 1/3] fix(fastapi): scope catch-all to its backend Refs #4234 --- CHANGELOG.md | 1 + dash/backends/_fastapi.py | 17 +++--- tests/backend_tests/test_fastapi_catchall.py | 64 ++++++++++++++++++++ 3 files changed, 74 insertions(+), 8 deletions(-) create mode 100644 tests/backend_tests/test_fastapi_catchall.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 038f1bd9fc..312ad29283 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ This project adheres to [Semantic Versioning](https://semver.org/). ### Fixed - [#4218](https://github.com/plotly/dash/pull/4218) Fix `pages_folder` written with `/` on Windows, such as `"src/pages"`, giving wrong page module names and paths. Fixes [#4217](https://github.com/plotly/dash/issues/4217). - [#4220](https://github.com/plotly/dash/pull/4220) Fix the `DASH_VALIDATE_CALLBACKS` environment variable being ignored, although `Dash.run` and `Dash.enable_dev_tools` document it for `dev_tools_validate_callbacks`. Fixes [#4219](https://github.com/plotly/dash/issues/4219). +- Fix the FastAPI catch-all route being registered on the wrong Dash app when multiple apps share a process. Each backend now registers its route once, even when lifespan restarts. Fixes [#4234](https://github.com/plotly/dash/issues/4234). ## [4.5.2] - 2026-11-27 diff --git a/dash/backends/_fastapi.py b/dash/backends/_fastapi.py index 3d261c78f2..271708c2b7 100644 --- a/dash/backends/_fastapi.py +++ b/dash/backends/_fastapi.py @@ -38,7 +38,7 @@ import janus from dash.fingerprint import check_fingerprint -from dash import _validate, get_app +from dash import _validate from dash._streaming import ( STREAM_HEADERS, STREAM_MIMETYPE, @@ -334,8 +334,7 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: if scope["type"] == "lifespan": try: - dash_app = get_app() - dash_app.backend._setup_catchall() + self.dash_server._setup_catchall(self.dash_app) except Exception: # pylint: disable=broad-exception-caught traceback.print_exc() await self._initialize_dev_tools() @@ -447,6 +446,8 @@ def __init__(self, server: FastAPI): self._before_request_funcs: List[Callable[[], Any]] = [] self._after_request_funcs: List[Callable[[], Any]] = [] self._enable_timing = False + self._catchall_registered = False + self._catchall_lock = threading.Lock() def __call__(self, *args: Any, **kwargs: Any): # ASGI: pass through to FastAPI @@ -512,9 +513,10 @@ def setup_catchall(self, dash_app: Dash): process the request and then return the appropriate response (e.g., 404 if no Dash route matches). """ - def _setup_catchall(self): - try: - dash_app = get_app() + def _setup_catchall(self, dash_app: Dash): + with self._catchall_lock: + if self._catchall_registered: + return async def catchall(request: Request): token = set_current_request(request) @@ -525,8 +527,7 @@ async def catchall(request: Request): # pylint: disable=protected-access self.add_url_rule("{path:path}", catchall, methods=["GET"]) - except Exception: # pylint: disable=broad-exception-caught - traceback.print_exc() + self._catchall_registered = True def add_url_rule( self, diff --git a/tests/backend_tests/test_fastapi_catchall.py b/tests/backend_tests/test_fastapi_catchall.py new file mode 100644 index 0000000000..24095e5f3c --- /dev/null +++ b/tests/backend_tests/test_fastapi_catchall.py @@ -0,0 +1,64 @@ +"""Catch-all routing is scoped to each FastAPI backend and registered once.""" + +import pytest + +from dash import Dash, html + +pytest.importorskip("fastapi") + + +def _make_app(title): + app = Dash(__name__, backend="fastapi", title=title) + app.layout = html.Div(title) + return app + + +def test_fastapi_catchall_is_bound_to_its_app(): + from starlette.testclient import TestClient + + first = _make_app("First app") + second = _make_app("Second app") + + for app in (first, second): + with TestClient(app.server) as client: + response = client.get("/reports") + assert response.status_code == 200 + assert f"{app.title}" in response.text + + +def test_fastapi_catchall_is_registered_once_after_custom_routes(): + from starlette.testclient import TestClient + + app = _make_app("Reports") + + @app.server.get("/api/status") + def status(): + return {"ok": True} + + for _ in range(2): + with TestClient(app.server) as client: + assert client.get("/api/status").json() == {"ok": True} + assert client.get("/reports").status_code == 200 + catchalls = [ + route + for route in app.server.routes + if getattr(route, "path", "").lstrip("/") == "{path:path}" + ] + assert len(catchalls) == 1 + + +def test_fastapi_catchall_retries_failed_registration(monkeypatch): + from starlette.testclient import TestClient + + app = _make_app("Reports") + + def fail_registration(*_args, **_kwargs): + raise RuntimeError("Could not register route") + + with monkeypatch.context() as patch: + patch.setattr(app.backend, "add_url_rule", fail_registration) + with TestClient(app.server) as client: + assert client.get("/reports").status_code == 404 + + with TestClient(app.server) as client: + assert client.get("/reports").status_code == 200 From 04457e0a67cd66a2a7d9cb5a05aa62b8ae11facd Mon Sep 17 00:00:00 2001 From: Ethan Zhang <33052368+c0debeez@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:59:58 +0800 Subject: [PATCH 2/3] docs: link FastAPI fix PR in changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 312ad29283..eb3235f390 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ This project adheres to [Semantic Versioning](https://semver.org/). ### Fixed - [#4218](https://github.com/plotly/dash/pull/4218) Fix `pages_folder` written with `/` on Windows, such as `"src/pages"`, giving wrong page module names and paths. Fixes [#4217](https://github.com/plotly/dash/issues/4217). - [#4220](https://github.com/plotly/dash/pull/4220) Fix the `DASH_VALIDATE_CALLBACKS` environment variable being ignored, although `Dash.run` and `Dash.enable_dev_tools` document it for `dev_tools_validate_callbacks`. Fixes [#4219](https://github.com/plotly/dash/issues/4219). -- Fix the FastAPI catch-all route being registered on the wrong Dash app when multiple apps share a process. Each backend now registers its route once, even when lifespan restarts. Fixes [#4234](https://github.com/plotly/dash/issues/4234). +- [#4235](https://github.com/plotly/dash/pull/4235) Fix FastAPI catch-all registration so each Dash app registers its own route once, even when lifespan restarts. Fixes [#4234](https://github.com/plotly/dash/issues/4234). ## [4.5.2] - 2026-11-27 From f1e11c8e56f4a6b34b242546fcb14f40e0338566 Mon Sep 17 00:00:00 2001 From: c0debeez <33052368+c0debeez@users.noreply.github.com> Date: Thu, 3 Dec 2026 12:19:07 +0800 Subject: [PATCH 3/3] Dispatch FastAPI deep links through the router fallback --- CHANGELOG.md | 2 +- dash/backends/_fastapi.py | 93 ++++++---- tests/backend_tests/test_fastapi_catchall.py | 169 ++++++++++++++----- 3 files changed, 190 insertions(+), 74 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index eb3235f390..b8df35d816 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ This project adheres to [Semantic Versioning](https://semver.org/). ### Fixed - [#4218](https://github.com/plotly/dash/pull/4218) Fix `pages_folder` written with `/` on Windows, such as `"src/pages"`, giving wrong page module names and paths. Fixes [#4217](https://github.com/plotly/dash/issues/4217). - [#4220](https://github.com/plotly/dash/pull/4220) Fix the `DASH_VALIDATE_CALLBACKS` environment variable being ignored, although `Dash.run` and `Dash.enable_dev_tools` document it for `dev_tools_validate_callbacks`. Fixes [#4219](https://github.com/plotly/dash/issues/4219). -- [#4235](https://github.com/plotly/dash/pull/4235) Fix FastAPI catch-all registration so each Dash app registers its own route once, even when lifespan restarts. Fixes [#4234](https://github.com/plotly/dash/issues/4234). +- [#4235](https://github.com/plotly/dash/pull/4235) Fix FastAPI deep links for mounted Dash apps and disabled or repeated lifespans. Apps sharing a server respect their URL prefixes, and explicit routes take precedence even when added after startup. Fixes [#4234](https://github.com/plotly/dash/issues/4234). ## [4.5.2] - 2026-11-27 diff --git a/dash/backends/_fastapi.py b/dash/backends/_fastapi.py index 271708c2b7..f78fa35077 100644 --- a/dash/backends/_fastapi.py +++ b/dash/backends/_fastapi.py @@ -16,17 +16,18 @@ import os import subprocess import threading -import traceback from urllib.parse import urlparse try: from fastapi import FastAPI, Request, Response, Body from fastapi.responses import JSONResponse, RedirectResponse, StreamingResponse + from fastapi.routing import APIRoute from fastapi.staticfiles import StaticFiles from starlette.responses import Response as StarletteResponse from starlette.datastructures import Headers, MutableHeaders from starlette.exceptions import HTTPException from starlette.requests import HTTPConnection + from starlette.routing import Match from starlette.types import ASGIApp, Message, Scope, Receive, Send from starlette.websockets import WebSocket, WebSocketDisconnect, WebSocketState import uvicorn @@ -39,6 +40,7 @@ from dash.fingerprint import check_fingerprint from dash import _validate +from dash._get_app import app_context from dash._streaming import ( STREAM_HEADERS, STREAM_MIMETYPE, @@ -150,6 +152,45 @@ def get_current_request() -> Request: return req +def _index_handler(dash_app: Dash): + async def index(request: Request): + request_token = set_current_request(request) + app_token = app_context.set(dash_app) + try: + response = Response(content=dash_app.index(), media_type="text/html") + finally: + app_context.reset(app_token) + reset_current_request(request_token) + if request.method == "HEAD": + # Keep the representation's Content-Length without sending the body. + response.body = b"" + return response + + return index + + +class _DashIndexFallback: + """Try Dash indexes after the host router has exhausted its explicit routes.""" + + def __init__(self, fallback: ASGIApp): + self.fallback = fallback + self.routes: list[APIRoute] = [] + + def add_route(self, route: APIRoute) -> None: + self.routes.append(route) + # Every path has the same catch-all suffix; prefer the longest app prefix. + self.routes.sort(key=lambda item: len(item.path), reverse=True) + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + for route in self.routes: + match, child_scope = route.matches(scope) + if match == Match.FULL: + scope.update(child_scope) + await route.handle(scope, receive, send) + return + await self.fallback(scope, receive, send) + + _ENV_CONFIG = "_DASH_FASTAPI_CONFIG" @@ -333,10 +374,6 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: # Handle lifespan events (startup/shutdown) if scope["type"] == "lifespan": - try: - self.dash_server._setup_catchall(self.dash_app) - except Exception: # pylint: disable=broad-exception-caught - traceback.print_exc() await self._initialize_dev_tools() async def _receive_with_shutdown(): @@ -446,8 +483,6 @@ def __init__(self, server: FastAPI): self._before_request_funcs: List[Callable[[], Any]] = [] self._after_request_funcs: List[Callable[[], Any]] = [] self._enable_timing = False - self._catchall_registered = False - self._catchall_lock = threading.Lock() def __call__(self, *args: Any, **kwargs: Any): # ASGI: pass through to FastAPI @@ -499,35 +534,27 @@ async def wrapped(*_args, **_kwargs): return wrapped def setup_index(self, dash_app: Dash): - async def index(_request: Request): - return Response(content=dash_app.index(), media_type="text/html") - # pylint: disable=protected-access - dash_app._add_url("", index, methods=["GET"]) + dash_app._add_url("", _index_handler(dash_app), methods=["GET"]) def setup_catchall(self, dash_app: Dash): - """This is needed to ensure that all routes are handled by FastAPI - and passed through the middleware, which is necessary for features like authentication - and timing to work correctly on all routes. FastAPI will match this catch-all route - for any path that isn't matched by a more specific route, allowing the middleware to - process the request and then return the appropriate response (e.g., 404 if no Dash route matches). - """ - - def _setup_catchall(self, dash_app: Dash): - with self._catchall_lock: - if self._catchall_registered: - return - - async def catchall(request: Request): - token = set_current_request(request) - try: - return Response(content=dash_app.index(), media_type="text/html") - finally: - reset_current_request(token) - - # pylint: disable=protected-access - self.add_url_rule("{path:path}", catchall, methods=["GET"]) - self._catchall_registered = True + router = self.server.router + fallback = router.default + if not isinstance(fallback, _DashIndexFallback): + fallback = _DashIndexFallback(fallback) + router.default = fallback + + # Dispatch through FastAPI to preserve host dependencies and their overrides. + fallback.add_route( + router.route_class( + dash_app.config.routes_pathname_prefix + "{path:path}", + _index_handler(dash_app), + methods=["GET", "HEAD"], + dependencies=router.dependencies, + dependency_overrides_provider=router.dependency_overrides_provider, + include_in_schema=False, + ) + ) def add_url_rule( self, diff --git a/tests/backend_tests/test_fastapi_catchall.py b/tests/backend_tests/test_fastapi_catchall.py index 24095e5f3c..40d1455e5a 100644 --- a/tests/backend_tests/test_fastapi_catchall.py +++ b/tests/backend_tests/test_fastapi_catchall.py @@ -1,64 +1,153 @@ -"""Catch-all routing is scoped to each FastAPI backend and registered once.""" +"""Verify the public routing behavior of the FastAPI Dash backend.""" import pytest -from dash import Dash, html +from dash import Dash, get_app, html -pytest.importorskip("fastapi") +fastapi = pytest.importorskip("fastapi") +TestClient = pytest.importorskip("starlette.testclient").TestClient -def _make_app(title): - app = Dash(__name__, backend="fastapi", title=title) +def _make_app(title, **kwargs): + app = Dash(__name__, backend="fastapi", title=title, **kwargs) app.layout = html.Div(title) return app -def test_fastapi_catchall_is_bound_to_its_app(): - from starlette.testclient import TestClient +def _assert_index(client, path, app): + response = client.get(path) + assert response.status_code == 200 + assert f"{app.title}" in response.text - first = _make_app("First app") - second = _make_app("Second app") +def test_independent_servers(): + first = _make_app("First") + second = _make_app("Second") for app in (first, second): with TestClient(app.server) as client: - response = client.get("/reports") - assert response.status_code == 200 - assert f"{app.title}" in response.text + _assert_index(client, "/reports", app) -def test_fastapi_catchall_is_registered_once_after_custom_routes(): - from starlette.testclient import TestClient - +def test_without_lifespan(): app = _make_app("Reports") - - @app.server.get("/api/status") - def status(): - return {"ok": True} - - for _ in range(2): - with TestClient(app.server) as client: - assert client.get("/api/status").json() == {"ok": True} - assert client.get("/reports").status_code == 200 - catchalls = [ - route - for route in app.server.routes - if getattr(route, "path", "").lstrip("/") == "{path:path}" - ] - assert len(catchalls) == 1 + client = TestClient(app.server) + try: + _assert_index(client, "/reports", app) + finally: + client.close() -def test_fastapi_catchall_retries_failed_registration(monkeypatch): - from starlette.testclient import TestClient - +def test_repeated_lifespan_and_late_route(): app = _make_app("Reports") + with TestClient(app.server) as client: + _assert_index(client, "/reports", app) - def fail_registration(*_args, **_kwargs): - raise RuntimeError("Could not register route") + @app.server.get("/api/status") + async def status(): + return {"ok": True} - with monkeypatch.context() as patch: - patch.setattr(app.backend, "add_url_rule", fail_registration) - with TestClient(app.server) as client: - assert client.get("/reports").status_code == 404 + assert client.get("/api/status").json() == {"ok": True} with TestClient(app.server) as client: - assert client.get("/reports").status_code == 200 + assert client.get("/api/status").json() == {"ok": True} + _assert_index(client, "/reports", app) + + +@pytest.mark.parametrize("prefix", ["/", "/app/"]) +def test_mounted_app(prefix): + parent = fastapi.FastAPI() + child = _make_app( + "Mounted", + routes_pathname_prefix=prefix, + requests_pathname_prefix="/dash" + prefix, + ) + parent.mount("/dash", child.server) + with TestClient(parent) as client: + _assert_index(client, "/dash" + prefix + "reports", child) + assert client.get("/dash" + prefix + "_dash-layout").json()["type"] == "Div" + assert client.get("/reports").status_code == 404 + if prefix != "/": + assert client.get("/dash/other").status_code == 404 + + +def test_prefix_and_http_methods(): + app = _make_app("Reports", url_base_pathname="/app/") + with TestClient(app.server) as client: + _assert_index(client, "/app/reports", app) + assert client.get("/other").status_code == 404 + assert client.get("/application/reports").status_code == 404 + assert client.post("/app/reports").status_code == 404 + response = client.head("/app/reports") + assert response.status_code == 200 + assert response.content == b"" + assert int(response.headers["content-length"]) > 0 + + +@pytest.mark.parametrize("prefixes", [("/", "/a/"), ("/a/", "/")]) +def test_shared_server_prefers_longest_prefix(prefixes): + server = fastapi.FastAPI() + apps = { + prefix: _make_app(f"App {prefix}", server=server, url_base_pathname=prefix) + for prefix in prefixes + } + with TestClient(server) as client: + _assert_index(client, "/reports", apps["/"]) + _assert_index(client, "/a/reports", apps["/a/"]) + _assert_index(client, "/ab/reports", apps["/"]) + + +def test_preserves_custom_fallback_and_explicit_errors(): + from starlette.responses import PlainTextResponse + + server = fastapi.FastAPI() + + async def fallback(scope, receive, send): + await PlainTextResponse("custom fallback", status_code=404)( + scope, receive, send + ) + + server.router.default = fallback + app = _make_app("Reports", server=server, url_base_pathname="/app/") + + @server.get("/app/missing") + async def missing(): + raise fastapi.HTTPException(status_code=404, detail="missing record") + + with TestClient(server) as client: + _assert_index(client, "/app/reports", app) + assert client.get("/other").text == "custom fallback" + assert client.get("/app/missing").json() == {"detail": "missing record"} + assert client.post("/app/missing").status_code == 405 + + +def test_deep_link_runs_host_dependencies_and_overrides(): + calls = [] + + async def record(): + calls.append("dependency") + + async def override(): + calls.append("override") + + server = fastapi.FastAPI(dependencies=[fastapi.Depends(record)]) + app = _make_app("Reports", server=server) + with TestClient(server) as client: + _assert_index(client, "/reports", app) + server.dependency_overrides[record] = override + _assert_index(client, "/reports", app) + assert calls == ["dependency", "override"] + + +def test_index_renders_with_its_app_context(): + class ContextDash(Dash): + def interpolate_index(self, **kwargs): + kwargs["title"] = get_app().title + return super().interpolate_index(**kwargs) + + server = fastapi.FastAPI() + first = ContextDash(__name__, server=server, backend="fastapi", title="First") + first.layout = html.Div("First") + _make_app("Second", server=server, url_base_pathname="/a/") + with TestClient(server) as client: + _assert_index(client, "/", first) + _assert_index(client, "/reports", first)