@@ -67,17 +67,18 @@ def function(func):
6767 return default_registry ().function (func )
6868
6969
70- def run (init : Callable [P , T ] , * args : P .args , ** kwargs : P .kwargs ) -> T :
71- """Run the default dispatch server on the given port . The default server
72- uses a function registry where functions tagged by the `@dispatch.function`
73- decorator are registered.
70+ def run (init : Optional [ Callable [P , None ]] = None , * args : P .args , ** kwargs : P .kwargs ):
71+ """Run the default dispatch server. The default server uses a function
72+ registry where functions tagged by the `@dispatch.function` decorator are
73+ registered.
7474
7575 This function is intended to be used with the `dispatch` CLI tool, which
7676 automatically configures environment variables to connect the local server
7777 to the Dispatch bridge API.
7878
7979 Args:
80- entrypoint: The entrypoint function to run. Defaults to a no-op function.
80+ init: An initialization function called after binding the server address
81+ but before entering the event loop to handle requests.
8182
8283 args: Positional arguments to pass to the entrypoint.
8384
@@ -86,32 +87,14 @@ def run(init: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T:
8687 Returns:
8788 The return value of the entrypoint function.
8889 """
89- with serve ():
90- return init (* args , ** kwargs )
91-
92-
93- @contextmanager
94- def serve (
95- address : str = os .environ .get ("DISPATCH_ENDPOINT_ADDR" , "localhost:8000" ),
96- poll_interval : float = 0.5 ,
97- ):
98- """Returns a context manager managing the operation of a Disaptch server
99- running on the given address. The server is initialized before the context
100- manager yields, then runs forever until the the program is interrupted.
101-
102- Args:
103- address: The address to bind the server to. Defaults to the value of the
104- DISPATCH_ENDPOINT_ADDR environment variable, or 'localhost:8000' if
105- it wasn't set.
106-
107- poll_interval: Poll for shutdown every poll_interval seconds.
108- Defaults to 0.5 seconds.
109- """
90+ address = os .environ .get ("DISPATCH_ENDPOINT_ADDR" , "localhost:8000" )
11091 parsed_url = urlsplit ("//" + address )
11192 server_address = (parsed_url .hostname or "" , parsed_url .port or 0 )
11293 server = ThreadingHTTPServer (server_address , Dispatch (default_registry ()))
11394 try :
114- yield server
115- server .serve_forever (poll_interval = poll_interval )
95+ if init is not None :
96+ init (* args , ** kwargs )
97+ server .serve_forever ()
11698 finally :
99+ server .shutdown ()
117100 server .server_close ()
0 commit comments