-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
fixing issue where FastAPI would not allow new paths to be added #3668
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
BSd3v
wants to merge
1
commit into
plotly:v4.1
Choose a base branch
from
BSd3v:v4.1-fix-FastAPI-paths
base: v4.1
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+42
−9
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -28,10 +28,11 @@ | |
| ) from _err | ||
|
|
||
| from dash.fingerprint import check_fingerprint | ||
| from dash import _validate | ||
| from dash import _validate, get_app | ||
| from dash.exceptions import PreventUpdate | ||
| from .base_server import BaseDashServer, RequestAdapter, ResponseAdapter | ||
| from ._utils import format_traceback_html | ||
| import traceback | ||
|
|
||
| if TYPE_CHECKING: # pragma: no cover - typing only | ||
| from dash import Dash | ||
|
|
@@ -122,8 +123,12 @@ async def _initialize_dev_tools(self) -> None: | |
| self.dash_app.enable_dev_tools(**config, first_run=False) | ||
| self._dev_tools_initialized = True | ||
|
|
||
| def _setup_timing(self, request: Request) -> None: | ||
| async def _setup_timing(self, request: Request) -> None: | ||
| """Set up timing information for the request.""" | ||
| try: | ||
| request.state.json_body = await request.json() if request.headers.get("content-type", "").startswith("application/json") else None | ||
| except: | ||
| request.state.json_body = None | ||
| if self.enable_timing: | ||
| request.state.timing_information = { | ||
| "__dash_server": {"dur": time.time(), "desc": None} | ||
|
|
@@ -179,6 +184,12 @@ async def _handle_error( | |
| 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: | ||
| print("Error during catch-all setup:") | ||
| print(traceback.format_exc()) | ||
| await self._initialize_dev_tools() | ||
| await self.app(scope, receive, send) | ||
| return | ||
|
|
@@ -193,7 +204,7 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: | |
| token = set_current_request(request) | ||
|
|
||
| try: | ||
| self._setup_timing(request) | ||
| await self._setup_timing(request) | ||
| await self._run_before_hooks() | ||
|
|
||
| await self.app(scope, receive, send) | ||
|
|
@@ -275,11 +286,24 @@ async def index(_request: Request): | |
| dash_app._add_url("", index, methods=["GET"]) | ||
|
|
||
| def setup_catchall(self, dash_app: Dash): | ||
| async def catchall(_request: Request): | ||
| return Response(content=dash_app.index(), media_type="text/html") | ||
| '''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).''' | ||
|
|
||
| # pylint: disable=protected-access | ||
| dash_app._add_url("{path:path}", catchall, methods=["GET"]) | ||
|
|
||
| def _setup_catchall(self): | ||
| try: | ||
| print("Setting up catch-all route for unmatched paths") | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Remove print or replace with a logger.debug call. |
||
| dash_app = get_app() | ||
| async def catchall(_request: Request): | ||
| return Response(content=dash_app.index(), media_type="text/html") | ||
|
|
||
| # pylint: disable=protected-access | ||
| self.add_url_rule("{path:path}", catchall, methods=["GET"]) | ||
| except: | ||
| print(traceback.format_exc()) | ||
|
|
||
| def add_url_rule( | ||
| self, | ||
|
|
@@ -289,6 +313,7 @@ def add_url_rule( | |
| methods: list[str] | None = None, | ||
| include_in_schema: bool = False, | ||
| ): | ||
| print(f"Adding URL rule: {rule} -> {view_func} (endpoint: {endpoint}, methods: {methods})") | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. logger.debug |
||
| if rule == "": | ||
| rule = "/" | ||
| if isinstance(view_func, str): | ||
|
|
@@ -481,7 +506,7 @@ def add_redirect_rule(self, app, fullname, path): | |
| def serve_callback(self, dash_app: Dash): | ||
| async def _dispatch(request: Request): | ||
| # pylint: disable=protected-access | ||
| body = await request.json() | ||
| body = self.request_adapter().get_json() | ||
| cb_ctx = dash_app._initialize_context( | ||
| body | ||
| ) # pylint: disable=protected-access | ||
|
|
@@ -641,5 +666,13 @@ def origin(self): | |
| def path(self): | ||
| return self._request.url.path | ||
|
|
||
| async def _get_json(self, request: Request=None): | ||
| req = self._request | ||
| if not hasattr(req.state, "json_body"): | ||
| req.state.json_body = await request.json() | ||
| return req.state.json_body | ||
|
|
||
| def get_json(self): | ||
| return asyncio.run(self._request.json()) | ||
| if not hasattr(self, "_request") or self._request is None: | ||
| self._request = get_current_request() | ||
| return self._request.state.json_body | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
traceback.print_exc()should be enough.