@@ -372,6 +372,7 @@ class Dash:
372
372
"""
373
373
374
374
_plotlyjs_url : str
375
+ STARTUP_ROUTES = []
375
376
376
377
def __init__ ( # pylint: disable=too-many-statements
377
378
self ,
@@ -556,6 +557,7 @@ def __init__( # pylint: disable=too-many-statements
556
557
"JupyterDash is deprecated, use Dash instead.\n "
557
558
"See https://dash.plotly.com/dash-in-jupyter for more details."
558
559
)
560
+ self .setup_startup_routes ()
559
561
560
562
def init_app (self , app = None , ** kwargs ):
561
563
"""Initialize the parts of Dash that require a flask app."""
@@ -1626,6 +1628,38 @@ def display_content(path):
1626
1628
self .config .requests_pathname_prefix , path
1627
1629
)
1628
1630
1631
+ @staticmethod
1632
+ def add_startup_route (name , view_func , methods = ["POST" ]):
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
+
1629
1663
def _setup_dev_tools (self , ** kwargs ):
1630
1664
debug = kwargs .get ("debug" , False )
1631
1665
dev_tools = self ._dev_tools = AttributeDict ()
0 commit comments