app.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 on_exception(self, handler: Union[Callable, Awaitable]) -> None:
  29. """Called when an exception occurs.
  30. The callback has an optional parameter of `Exception`.
  31. """
  32. globals.exception_handlers.append(handler)
  33. def shutdown(self) -> None:
  34. """Shut down NiceGUI.
  35. This will programmatically stop the server.
  36. Only possible when auto-reload is disabled.
  37. """
  38. if globals.reload:
  39. raise Exception('calling shutdown() is not supported when auto-reload is enabled')
  40. globals.server.should_exit = True
  41. def add_static_files(self, path: str, directory: str) -> None:
  42. """Add static files.
  43. `add_static_files()` makes a local directory available at the specified endpoint, e.g. `'/static'`.
  44. This is useful for providing local data like images to the frontend.
  45. Otherwise the browser would not be able to access the files.
  46. Do only put non-security-critical files in there, as they are accessible to everyone.
  47. :param path: string that starts with a slash "/"
  48. :param directory: folder with static files to serve under the given path
  49. """
  50. globals.app.mount(path, StaticFiles(directory=directory))
  51. def remove_route(self, path: str) -> None:
  52. """Remove routes with the given path."""
  53. self.routes[:] = [r for r in self.routes if getattr(r, 'path', None) != path]