diff --git a/CHANGELOG.md b/CHANGELOG.md index 038f1bd9fc..b8df35d816 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). +- [#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 3d261c78f2..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 @@ -38,7 +39,8 @@ import janus from dash.fingerprint import check_fingerprint -from dash import _validate, get_app +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,11 +374,6 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: # Handle lifespan events (startup/shutdown) if scope["type"] == "lifespan": - try: - dash_app = get_app() - dash_app.backend._setup_catchall() - except Exception: # pylint: disable=broad-exception-caught - traceback.print_exc() await self._initialize_dev_tools() async def _receive_with_shutdown(): @@ -498,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): - try: - dash_app = get_app() - - 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"]) - except Exception: # pylint: disable=broad-exception-caught - traceback.print_exc() + 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 new file mode 100644 index 0000000000..40d1455e5a --- /dev/null +++ b/tests/backend_tests/test_fastapi_catchall.py @@ -0,0 +1,153 @@ +"""Verify the public routing behavior of the FastAPI Dash backend.""" + +import pytest + +from dash import Dash, get_app, html + +fastapi = pytest.importorskip("fastapi") +TestClient = pytest.importorskip("starlette.testclient").TestClient + + +def _make_app(title, **kwargs): + app = Dash(__name__, backend="fastapi", title=title, **kwargs) + app.layout = html.Div(title) + return app + + +def _assert_index(client, path, app): + response = client.get(path) + assert response.status_code == 200 + assert f"{app.title}" in response.text + + +def test_independent_servers(): + first = _make_app("First") + second = _make_app("Second") + for app in (first, second): + with TestClient(app.server) as client: + _assert_index(client, "/reports", app) + + +def test_without_lifespan(): + app = _make_app("Reports") + client = TestClient(app.server) + try: + _assert_index(client, "/reports", app) + finally: + client.close() + + +def test_repeated_lifespan_and_late_route(): + app = _make_app("Reports") + with TestClient(app.server) as client: + _assert_index(client, "/reports", app) + + @app.server.get("/api/status") + async def status(): + return {"ok": True} + + assert client.get("/api/status").json() == {"ok": True} + + with TestClient(app.server) as client: + 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)