nicegui.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. import asyncio
  2. import mimetypes
  3. import time
  4. import urllib.parse
  5. from pathlib import Path
  6. from typing import Dict, Optional
  7. from fastapi import HTTPException, Request
  8. from fastapi.middleware.gzip import GZipMiddleware
  9. from fastapi.responses import FileResponse, Response
  10. from fastapi.staticfiles import StaticFiles
  11. from fastapi_socketio import SocketManager
  12. from . import (background_tasks, binding, favicon, globals, json, outbox, # pylint: disable=redefined-builtin
  13. run_executor, welcome)
  14. from .app import App
  15. from .client import Client
  16. from .dependencies import js_components, libraries
  17. from .error import error_content
  18. from .helpers import is_file, safe_invoke
  19. from .json import NiceGUIJSONResponse
  20. from .middlewares import RedirectWithPrefixMiddleware
  21. from .page import page
  22. from .version import __version__
  23. globals.app = app = App(default_response_class=NiceGUIJSONResponse)
  24. # NOTE we use custom json module which wraps orjson
  25. socket_manager = SocketManager(app=app, mount_location='/_nicegui_ws/', json=json)
  26. globals.sio = sio = socket_manager._sio # pylint: disable=protected-access
  27. mimetypes.add_type('text/javascript', '.js')
  28. mimetypes.add_type('text/css', '.css')
  29. app.add_middleware(GZipMiddleware)
  30. app.add_middleware(RedirectWithPrefixMiddleware)
  31. static_files = StaticFiles(
  32. directory=(Path(__file__).parent / 'static').resolve(),
  33. follow_symlink=True,
  34. )
  35. app.mount(f'/_nicegui/{__version__}/static', static_files, name='static')
  36. globals.index_client = Client(page('/'), shared=True).__enter__() # pylint: disable=unnecessary-dunder-call
  37. @app.get('/')
  38. def index(request: Request) -> Response:
  39. return globals.index_client.build_response(request)
  40. @app.get(f'/_nicegui/{__version__}' + '/libraries/{key:path}')
  41. def get_library(key: str) -> FileResponse:
  42. is_map = key.endswith('.map')
  43. dict_key = key[:-4] if is_map else key
  44. if dict_key in libraries:
  45. path = libraries[dict_key].path
  46. if is_map:
  47. path = path.with_name(path.name + '.map')
  48. if path.exists():
  49. headers = {'Cache-Control': 'public, max-age=3600'}
  50. return FileResponse(path, media_type='text/javascript', headers=headers)
  51. raise HTTPException(status_code=404, detail=f'library "{key}" not found')
  52. @app.get(f'/_nicegui/{__version__}' + '/components/{key:path}')
  53. def get_component(key: str) -> FileResponse:
  54. if key in js_components and js_components[key].path.exists():
  55. headers = {'Cache-Control': 'public, max-age=3600'}
  56. return FileResponse(js_components[key].path, media_type='text/javascript', headers=headers)
  57. raise HTTPException(status_code=404, detail=f'component "{key}" not found')
  58. @app.on_event('startup')
  59. def handle_startup(with_welcome_message: bool = True) -> None:
  60. if not globals.ui_run_has_been_called:
  61. raise RuntimeError('\n\n'
  62. 'You must call ui.run() to start the server.\n'
  63. 'If ui.run() is behind a main guard\n'
  64. ' if __name__ == "__main__":\n'
  65. 'remove the guard or replace it with\n'
  66. ' if __name__ in {"__main__", "__mp_main__"}:\n'
  67. 'to allow for multiprocessing.')
  68. if globals.favicon:
  69. if is_file(globals.favicon):
  70. globals.app.add_route('/favicon.ico', lambda _: FileResponse(globals.favicon)) # type: ignore
  71. else:
  72. globals.app.add_route('/favicon.ico', lambda _: favicon.get_favicon_response())
  73. else:
  74. globals.app.add_route('/favicon.ico', lambda _: FileResponse(Path(__file__).parent / 'static' / 'favicon.ico'))
  75. globals.state = globals.State.STARTING
  76. globals.loop = asyncio.get_running_loop()
  77. with globals.index_client:
  78. for t in globals.startup_handlers:
  79. safe_invoke(t)
  80. background_tasks.create(binding.loop())
  81. background_tasks.create(outbox.loop())
  82. background_tasks.create(prune_clients())
  83. background_tasks.create(prune_slot_stacks())
  84. globals.state = globals.State.STARTED
  85. if with_welcome_message:
  86. background_tasks.create(welcome.print_message())
  87. if globals.air:
  88. background_tasks.create(globals.air.connect())
  89. @app.on_event('shutdown')
  90. async def handle_shutdown() -> None:
  91. if app.native.main_window:
  92. app.native.main_window.signal_server_shutdown()
  93. globals.state = globals.State.STOPPING
  94. with globals.index_client:
  95. for t in globals.shutdown_handlers:
  96. safe_invoke(t)
  97. run_executor.tear_down()
  98. globals.state = globals.State.STOPPED
  99. if globals.air:
  100. await globals.air.disconnect()
  101. @app.exception_handler(404)
  102. async def exception_handler_404(request: Request, exception: Exception) -> Response:
  103. globals.log.warning(f'{request.url} not found')
  104. with Client(page('')) as client:
  105. error_content(404, exception)
  106. return client.build_response(request, 404)
  107. @app.exception_handler(Exception)
  108. async def exception_handler_500(request: Request, exception: Exception) -> Response:
  109. globals.log.exception(exception)
  110. with Client(page('')) as client:
  111. error_content(500, exception)
  112. return client.build_response(request, 500)
  113. @sio.on('handshake')
  114. def on_handshake(sid: str) -> bool:
  115. client = get_client(sid)
  116. if not client:
  117. return False
  118. client.environ = sio.get_environ(sid)
  119. sio.enter_room(sid, client.id)
  120. handle_handshake(client)
  121. return True
  122. def handle_handshake(client: Client) -> None:
  123. for t in client.connect_handlers:
  124. safe_invoke(t, client)
  125. for t in globals.connect_handlers:
  126. safe_invoke(t, client)
  127. @sio.on('disconnect')
  128. def on_disconnect(sid: str) -> None:
  129. client = get_client(sid)
  130. if not client:
  131. return
  132. handle_disconnect(client)
  133. def handle_disconnect(client: Client) -> None:
  134. if not client.shared:
  135. delete_client(client.id)
  136. for t in client.disconnect_handlers:
  137. safe_invoke(t, client)
  138. for t in globals.disconnect_handlers:
  139. safe_invoke(t, client)
  140. @sio.on('event')
  141. def on_event(sid: str, msg: Dict) -> None:
  142. client = get_client(sid)
  143. if not client or not client.has_socket_connection:
  144. return
  145. handle_event(client, msg)
  146. def handle_event(client: Client, msg: Dict) -> None:
  147. with client:
  148. sender = client.elements.get(msg['id'])
  149. if sender:
  150. msg['args'] = [None if arg is None else json.loads(arg) for arg in msg.get('args', [])]
  151. if len(msg['args']) == 1:
  152. msg['args'] = msg['args'][0]
  153. sender._handle_event(msg) # pylint: disable=protected-access
  154. @sio.on('javascript_response')
  155. def on_javascript_response(sid: str, msg: Dict) -> None:
  156. client = get_client(sid)
  157. if not client:
  158. return
  159. handle_javascript_response(client, msg)
  160. def handle_javascript_response(client: Client, msg: Dict) -> None:
  161. client.waiting_javascript_commands[msg['request_id']] = msg['result']
  162. def get_client(sid: str) -> Optional[Client]:
  163. query_bytes: bytearray = sio.get_environ(sid)['asgi.scope']['query_string']
  164. query = urllib.parse.parse_qs(query_bytes.decode())
  165. client_id = query['client_id'][0]
  166. return globals.clients.get(client_id)
  167. async def prune_clients() -> None:
  168. while True:
  169. stale_clients = [
  170. id
  171. for id, client in globals.clients.items()
  172. if not client.shared and not client.has_socket_connection and client.created < time.time() - 60.0
  173. ]
  174. for client_id in stale_clients:
  175. delete_client(client_id)
  176. await asyncio.sleep(10)
  177. async def prune_slot_stacks() -> None:
  178. while True:
  179. running = [
  180. id(task)
  181. for task in asyncio.tasks.all_tasks()
  182. if not task.done() and not task.cancelled()
  183. ]
  184. stale = [
  185. id_
  186. for id_ in globals.slot_stacks
  187. if id_ not in running
  188. ]
  189. for id_ in stale:
  190. del globals.slot_stacks[id_]
  191. await asyncio.sleep(10)
  192. def delete_client(client_id: str) -> None:
  193. globals.clients.pop(client_id).remove_all_elements()