app.py 7.2 KB

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