lifecycle.py 980 B

12345678910111213141516171819202122232425262728293031
  1. from typing import Awaitable, Callable, Union
  2. import justpy as jp
  3. from . import globals
  4. def on_connect(self, handler: Union[Callable, Awaitable]):
  5. globals.connect_handlers.append(handler)
  6. def on_disconnect(self, handler: Union[Callable, Awaitable]):
  7. globals.disconnect_handlers.append(handler)
  8. def on_startup(self, handler: Union[Callable, Awaitable]):
  9. if globals.state == globals.State.STARTED:
  10. raise RuntimeError('Unable to register another startup handler. NiceGUI has already been started.')
  11. globals.startup_handlers.append(handler)
  12. def on_shutdown(self, handler: Union[Callable, Awaitable]):
  13. globals.shutdown_handlers.append(handler)
  14. async def shutdown(self) -> None:
  15. if globals.config.reload:
  16. raise Exception('ui.shutdown is not supported when auto-reload is enabled')
  17. for socket in [s for page in jp.WebPage.sockets.values() for s in page.values()]:
  18. await socket.close()
  19. globals.server.should_exit = True