Skip to content

Commit 93195fa

Browse files
authored
Merge pull request #2832 from plotly/add-startup-route-setup
Add startup route setup
2 parents d098e76 + 92f5fab commit 93195fa

File tree

3 files changed

+57
-0
lines changed

3 files changed

+57
-0
lines changed

Diff for: CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ This project adheres to [Semantic Versioning](https://semver.org/).
66

77
## Added
88

9+
- [#2832](https://github.com/plotly/dash/pull/2832) Add dash startup route setup on Dash init.
910
- [#2819](https://github.com/plotly/dash/pull/2819) Add dash subcomponents receive additional parameters passed by the parent component. Fixes [#2814](https://github.com/plotly/dash/issues/2814).
1011
- [#2826](https://github.com/plotly/dash/pull/2826) When using Pages, allows for `app.title` and (new) `app.description` to be used as defaults for the page title and description. Fixes [#2811](https://github.com/plotly/dash/issues/2811).
1112
- [#2795](https://github.com/plotly/dash/pull/2795) Allow list of components to be passed as layout.

Diff for: dash/dash.py

+35
Original file line numberDiff line numberDiff line change
@@ -372,6 +372,7 @@ class Dash:
372372
"""
373373

374374
_plotlyjs_url: str
375+
STARTUP_ROUTES: list = []
375376

376377
def __init__( # pylint: disable=too-many-statements
377378
self,
@@ -556,6 +557,7 @@ def __init__( # pylint: disable=too-many-statements
556557
"JupyterDash is deprecated, use Dash instead.\n"
557558
"See https://dash.plotly.com/dash-in-jupyter for more details."
558559
)
560+
self.setup_startup_routes()
559561

560562
def init_app(self, app=None, **kwargs):
561563
"""Initialize the parts of Dash that require a flask app."""
@@ -1626,6 +1628,39 @@ def display_content(path):
16261628
self.config.requests_pathname_prefix, path
16271629
)
16281630

1631+
@staticmethod
1632+
def add_startup_route(name, view_func, methods):
1633+
"""
1634+
Add a route to the app to be initialized at the end of Dash initialization.
1635+
Use this if the package requires a route to be added to the app, and you will not need to worry about at what point to add it.
1636+
1637+
:param name: The name of the route. eg "my-new-url/path".
1638+
:param view_func: The function to call when the route is requested. The function should return a JSON serializable object.
1639+
:param methods: The HTTP methods that the route should respond to. eg ["GET", "POST"] or either one.
1640+
"""
1641+
if not isinstance(name, str) or name.startswith("/"):
1642+
raise ValueError("name must be a string and should not start with '/'")
1643+
1644+
if not callable(view_func):
1645+
raise ValueError("view_func must be callable")
1646+
1647+
valid_methods = {"POST", "GET"}
1648+
if not set(methods).issubset(valid_methods):
1649+
raise ValueError(f"methods should only contain {valid_methods}")
1650+
1651+
if any(route[0] == name for route in Dash.STARTUP_ROUTES):
1652+
raise ValueError(f"Route name '{name}' is already in use.")
1653+
1654+
Dash.STARTUP_ROUTES.append((name, view_func, methods))
1655+
1656+
def setup_startup_routes(self):
1657+
"""
1658+
Initialize the startup routes stored in STARTUP_ROUTES.
1659+
"""
1660+
for _name, _view_func, _methods in self.STARTUP_ROUTES:
1661+
self._add_url(f"_dash_startup_route/{_name}", _view_func, _methods)
1662+
self.STARTUP_ROUTES = []
1663+
16291664
def _setup_dev_tools(self, **kwargs):
16301665
debug = kwargs.get("debug", False)
16311666
dev_tools = self._dev_tools = AttributeDict()

Diff for: tests/integration/test_integration.py

+21
Original file line numberDiff line numberDiff line change
@@ -511,3 +511,24 @@ def on_nested_click(n_clicks):
511511

512512
dash_duo.wait_for_element("#nested").click()
513513
dash_duo.wait_for_text_to_equal("#nested-output", "Clicked 1 times")
514+
515+
516+
def test_inin030_add_startup_route(dash_duo):
517+
url = "my-new-route"
518+
519+
def my_route_f():
520+
return "hello"
521+
522+
Dash.add_startup_route(url, my_route_f, ["POST"])
523+
524+
import requests
525+
526+
app = Dash(__name__)
527+
Dash.STARTUP_ROUTES = []
528+
app.layout = html.Div("Hello World")
529+
dash_duo.start_server(app)
530+
531+
url = f"{dash_duo.server_url}{app.config.requests_pathname_prefix}_dash_startup_route/{url}"
532+
response = requests.post(url)
533+
assert response.status_code == 200
534+
assert response.text == "hello"

0 commit comments

Comments
 (0)