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"