app.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. from pathlib import Path
  2. from typing import Awaitable, Callable, Optional, Union
  3. from fastapi import FastAPI, Request
  4. from fastapi.responses import FileResponse, StreamingResponse
  5. from fastapi.staticfiles import StaticFiles
  6. from . import globals, helpers
  7. from .native import Native
  8. from .storage import Storage
  9. class App(FastAPI):
  10. def __init__(self, **kwargs) -> None:
  11. super().__init__(**kwargs)
  12. self.native = Native()
  13. self.storage = Storage()
  14. def on_connect(self, handler: Union[Callable, Awaitable]) -> None:
  15. """Called every time a new client connects to NiceGUI.
  16. The callback has an optional parameter of `nicegui.Client`.
  17. """
  18. globals.connect_handlers.append(handler)
  19. def on_disconnect(self, handler: Union[Callable, Awaitable]) -> None:
  20. """Called every time a new client disconnects from NiceGUI.
  21. The callback has an optional parameter of `nicegui.Client`.
  22. """
  23. globals.disconnect_handlers.append(handler)
  24. def on_startup(self, handler: Union[Callable, Awaitable]) -> None:
  25. """Called when NiceGUI is started or restarted.
  26. Needs to be called before `ui.run()`.
  27. """
  28. if globals.state == globals.State.STARTED:
  29. raise RuntimeError('Unable to register another startup handler. NiceGUI has already been started.')
  30. globals.startup_handlers.append(handler)
  31. def on_shutdown(self, handler: Union[Callable, Awaitable]) -> None:
  32. """Called when NiceGUI is shut down or restarted.
  33. When NiceGUI is shut down or restarted, all tasks still in execution will be automatically canceled.
  34. """
  35. globals.shutdown_handlers.append(handler)
  36. def on_exception(self, handler: Callable) -> None:
  37. """Called when an exception occurs.
  38. The callback has an optional parameter of `Exception`.
  39. """
  40. globals.exception_handlers.append(handler)
  41. def shutdown(self) -> None:
  42. """Shut down NiceGUI.
  43. This will programmatically stop the server.
  44. Only possible when auto-reload is disabled.
  45. """
  46. if globals.reload:
  47. raise Exception('calling shutdown() is not supported when auto-reload is enabled')
  48. globals.server.should_exit = True
  49. def add_static_files(self, url_path: str, local_directory: Union[str, Path]) -> None:
  50. """Add a directory of static files.
  51. `add_static_files()` makes a local directory available at the specified endpoint, e.g. `'/static'`.
  52. This is useful for providing local data like images to the frontend.
  53. Otherwise the browser would not be able to access the files.
  54. Do only put non-security-critical files in there, as they are accessible to everyone.
  55. To make a single file accessible, you can use `add_static_file()`.
  56. For media files which should be streamed, you can use `add_media_files()` or `add_media_file()` instead.
  57. :param url_path: string that starts with a slash "/" and identifies the path at which the files should be served
  58. :param local_directory: local folder with files to serve as static content
  59. """
  60. if url_path == '/':
  61. raise ValueError('''Path cannot be "/", because it would hide NiceGUI's internal "/_nicegui" route.''')
  62. globals.app.mount(url_path, StaticFiles(directory=str(local_directory)))
  63. def add_static_file(self, *, local_file: Union[str, Path], url_path: Optional[str] = None) -> str:
  64. """Add a single static file.
  65. Allows a local file to be accessed online with enabled caching.
  66. If `url_path` is not specified, a path will be generated.
  67. To make a whole folder of files accessible, use `add_static_files()` instead.
  68. For media files which should be streamed, you can use `add_media_files()` or `add_media_file()` instead.
  69. :param local_file: local file to serve as static content
  70. :param url_path: string that starts with a slash "/" and identifies the path at which the file should be served (default: None -> auto-generated URL path)
  71. :return: URL path which can be used to access the file
  72. """
  73. file = Path(local_file).resolve()
  74. if not file.is_file():
  75. raise ValueError(f'File not found: {file}')
  76. if url_path is None:
  77. url_path = f'/_nicegui/auto/static/{helpers.hash_file_path(file)}/{file.name}'
  78. @self.get(url_path)
  79. def read_item() -> FileResponse:
  80. return FileResponse(file, headers={'Cache-Control': 'public, max-age=3600'})
  81. return url_path
  82. def add_media_files(self, url_path: str, local_directory: Union[str, Path]) -> None:
  83. """Add directory of media files.
  84. `add_media_files()` allows a local files to be streamed from a specified endpoint, e.g. `'/media'`.
  85. This should be used for media files to support proper streaming.
  86. Otherwise the browser would not be able to access and load the the files incrementally or jump to different positions in the stream.
  87. Do only put non-security-critical files in there, as they are accessible to everyone.
  88. To make a single file accessible via streaming, you can use `add_media_file()`.
  89. For small static files, you can use `add_static_files()` or `add_static_file()` instead.
  90. :param url_path: string that starts with a slash "/" and identifies the path at which the files should be served
  91. :param local_directory: local folder with files to serve as media content
  92. """
  93. @self.get(url_path + '/{filename:path}')
  94. def read_item(request: Request, filename: str) -> StreamingResponse:
  95. filepath = Path(local_directory) / filename
  96. if not filepath.is_file():
  97. return {'detail': 'Not Found'}, 404
  98. return helpers.get_streaming_response(filepath, request)
  99. def add_media_file(self, *, local_file: Union[str, Path], url_path: Optional[str] = None) -> str:
  100. """Add a single media file.
  101. Allows a local file to be streamed.
  102. If `url_path` is not specified, a path will be generated.
  103. To make a whole folder of media files accessible via streaming, use `add_media_files()` instead.
  104. For small static files, you can use `add_static_files()` or `add_static_file()` instead.
  105. :param local_file: local file to serve as media content
  106. :param url_path: string that starts with a slash "/" and identifies the path at which the file should be served (default: None -> auto-generated URL path)
  107. :return: URL path which can be used to access the file
  108. """
  109. file = Path(local_file).resolve()
  110. if not file.is_file():
  111. raise ValueError(f'File not found: {local_file}')
  112. if url_path is None:
  113. url_path = f'/_nicegui/auto/media/{helpers.hash_file_path(file)}/{file.name}'
  114. @self.get(url_path)
  115. def read_item(request: Request) -> StreamingResponse:
  116. return helpers.get_streaming_response(file, request)
  117. return url_path
  118. def remove_route(self, path: str) -> None:
  119. """Remove routes with the given path."""
  120. self.routes[:] = [r for r in self.routes if getattr(r, 'path', None) != path]