app.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. from typing import Awaitable, Callable, Union
  2. from fastapi import FastAPI
  3. from fastapi.staticfiles import StaticFiles
  4. from . import globals
  5. class App(FastAPI):
  6. def on_connect(self, handler: Union[Callable, Awaitable]) -> None:
  7. """Called every time a new client connects to NiceGUI.
  8. The callback has an optional parameter of `nicegui.Client`.
  9. """
  10. globals.connect_handlers.append(handler)
  11. def on_disconnect(self, handler: Union[Callable, Awaitable]) -> None:
  12. """Called every time a new client disconnects from NiceGUI.
  13. The callback has an optional parameter of `nicegui.Client`.
  14. """
  15. globals.disconnect_handlers.append(handler)
  16. def on_startup(self, handler: Union[Callable, Awaitable]) -> None:
  17. """Called when NiceGUI is started or restarted.
  18. Needs to be called before `ui.run()`.
  19. """
  20. if globals.state == globals.State.STARTED:
  21. raise RuntimeError('Unable to register another startup handler. NiceGUI has already been started.')
  22. globals.startup_handlers.append(handler)
  23. def on_shutdown(self, handler: Union[Callable, Awaitable]) -> None:
  24. """Called when NiceGUI is shut down or restarted.
  25. When NiceGUI is shut down or restarted, all tasks still in execution will be automatically canceled.
  26. """
  27. globals.shutdown_handlers.append(handler)
  28. def shutdown(self) -> None:
  29. """Programmatically shut down NiceGUI.
  30. Only possible when auto-reload is disabled.
  31. """
  32. if globals.reload:
  33. raise Exception('calling shutdown() is not supported when auto-reload is enabled')
  34. globals.server.should_exit = True
  35. def add_static_files(self, path: str, directory: str) -> None:
  36. """Add static files.
  37. `add_static_files()` makes a local directory available at the specified endpoint, e.g. `'/static'`.
  38. This is useful for providing local data like images to the frontend.
  39. Otherwise the browser would not be able to access the files.
  40. Do only put non-security-critical files in there, as they are accessible to everyone.
  41. :param path: string that starts with a slash "/"
  42. :param directory: folder with static files to serve under the given path
  43. """
  44. globals.app.mount(path, StaticFiles(directory=directory))