1
0

app.py 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. from typing import Awaitable, Callable, Union
  2. from fastapi import FastAPI
  3. from fastapi.staticfiles import StaticFiles
  4. from . import globals
  5. from .native import Native
  6. class App(FastAPI):
  7. def __init__(self, **kwargs) -> None:
  8. super().__init__(**kwargs)
  9. self.native = Native()
  10. def on_connect(self, handler: Union[Callable, Awaitable]) -> None:
  11. """Called every time a new client connects to NiceGUI.
  12. The callback has an optional parameter of `nicegui.Client`.
  13. """
  14. globals.connect_handlers.append(handler)
  15. def on_disconnect(self, handler: Union[Callable, Awaitable]) -> None:
  16. """Called every time a new client disconnects from NiceGUI.
  17. The callback has an optional parameter of `nicegui.Client`.
  18. """
  19. globals.disconnect_handlers.append(handler)
  20. def on_startup(self, handler: Union[Callable, Awaitable]) -> None:
  21. """Called when NiceGUI is started or restarted.
  22. Needs to be called before `ui.run()`.
  23. """
  24. if globals.state == globals.State.STARTED:
  25. raise RuntimeError('Unable to register another startup handler. NiceGUI has already been started.')
  26. globals.startup_handlers.append(handler)
  27. def on_shutdown(self, handler: Union[Callable, Awaitable]) -> None:
  28. """Called when NiceGUI is shut down or restarted.
  29. When NiceGUI is shut down or restarted, all tasks still in execution will be automatically canceled.
  30. """
  31. globals.shutdown_handlers.append(handler)
  32. def on_exception(self, handler: Union[Callable, Awaitable]) -> None:
  33. """Called when an exception occurs.
  34. The callback has an optional parameter of `Exception`.
  35. """
  36. globals.exception_handlers.append(handler)
  37. def shutdown(self) -> None:
  38. """Shut down NiceGUI.
  39. This will programmatically stop the server.
  40. Only possible when auto-reload is disabled.
  41. """
  42. if globals.reload:
  43. raise Exception('calling shutdown() is not supported when auto-reload is enabled')
  44. globals.server.should_exit = True
  45. def add_static_files(self, url_path: str, local_directory: str) -> None:
  46. """Add static files.
  47. `add_static_files()` makes a local directory available at the specified endpoint, e.g. `'/static'`.
  48. This is useful for providing local data like images to the frontend.
  49. Otherwise the browser would not be able to access the files.
  50. Do only put non-security-critical files in there, as they are accessible to everyone.
  51. :param url_path: string that starts with a slash "/" and identifies the path at which the files should be served
  52. :param local_directory: local folder with files to serve as static content
  53. """
  54. if url_path == '/':
  55. raise ValueError('''Path cannot be "/", because it would hide NiceGUI's internal "/_nicegui" route.''')
  56. globals.app.mount(url_path, StaticFiles(directory=local_directory))
  57. def remove_route(self, path: str) -> None:
  58. """Remove routes with the given path."""
  59. self.routes[:] = [r for r in self.routes if getattr(r, 'path', None) != path]