lifecycle.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. '''Lifecycle functions
  2. You can register coroutines or functions to be called for the following events:
  3. - `ui.lifecycle.on_startup`: called when NiceGUI is started or restarted
  4. - `ui.lifecycle.on_shutdown`: called when NiceGUI is shut down or restarted
  5. - `ui.lifecycle.on_connect`: called for each client which connects (optional argument: nicegui.Client)
  6. - `ui.lifecycle.on_disconnect`: called for each client which disconnects (optional argument: nicegui.Client)
  7. When NiceGUI is shut down or restarted, all tasks still in execution will be automatically canceled.
  8. '''
  9. from typing import Awaitable, Callable, Union
  10. from .. import globals
  11. def on_connect(handler: Union[Callable, Awaitable]) -> None:
  12. '''Called every time a new client connects to NiceGUI.
  13. The callback has an optional parameter of `nicegui.Client`.
  14. '''
  15. globals.connect_handlers.append(handler)
  16. def on_disconnect(handler: Union[Callable, Awaitable]) -> None:
  17. '''Called every time a new client disconnects from NiceGUI.
  18. The callback has an optional parameter of `nicegui.Client`.
  19. '''
  20. globals.disconnect_handlers.append(handler)
  21. def on_startup(handler: Union[Callable, Awaitable]) -> None:
  22. '''Called when NiceGUI is started or restarted.
  23. Needs to be called before `ui.run()`.
  24. '''
  25. if globals.state == globals.State.STARTED:
  26. raise RuntimeError('Unable to register another startup handler. NiceGUI has already been started.')
  27. globals.startup_handlers.append(handler)
  28. def on_shutdown(handler: Union[Callable, Awaitable]) -> None:
  29. '''Called when NiceGUI is shut down or restarted.'''
  30. globals.shutdown_handlers.append(handler)
  31. async def shutdown() -> None:
  32. '''Programmatically shut down NiceGUI.
  33. Only possible when auto-reload is disabled.
  34. '''
  35. if globals.reload:
  36. raise Exception('calling shutdown() is not supported when auto-reload is enabled')
  37. globals.server.should_exit = True