nicegui.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. import asyncio
  2. import mimetypes
  3. import urllib.parse
  4. from contextlib import asynccontextmanager
  5. from pathlib import Path
  6. from typing import Dict
  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 air, background_tasks, binding, core, favicon, helpers, json, outbox, run
  13. from .app import App
  14. from .client import Client
  15. from .dependencies import js_components, libraries
  16. from .error import error_content
  17. from .json import NiceGUIJSONResponse
  18. from .logging import log
  19. from .middlewares import RedirectWithPrefixMiddleware
  20. from .page import page
  21. from .slot import Slot
  22. from .version import __version__
  23. @asynccontextmanager
  24. async def _lifespan(_: App):
  25. _startup()
  26. yield
  27. await _shutdown()
  28. core.app = app = App(default_response_class=NiceGUIJSONResponse, lifespan=_lifespan)
  29. # NOTE we use custom json module which wraps orjson
  30. socket_manager = SocketManager(app=app, mount_location='/_nicegui_ws/', json=json)
  31. core.sio = sio = socket_manager._sio # pylint: disable=protected-access
  32. mimetypes.add_type('text/javascript', '.js')
  33. mimetypes.add_type('text/css', '.css')
  34. app.add_middleware(GZipMiddleware)
  35. app.add_middleware(RedirectWithPrefixMiddleware)
  36. static_files = StaticFiles(
  37. directory=(Path(__file__).parent / 'static').resolve(),
  38. follow_symlink=True,
  39. )
  40. app.mount(f'/_nicegui/{__version__}/static', static_files, name='static')
  41. Client.auto_index_client = Client(page('/'), shared=True).__enter__() # pylint: disable=unnecessary-dunder-call
  42. @app.get('/')
  43. def _get_index(request: Request) -> Response:
  44. return Client.auto_index_client.build_response(request)
  45. @app.get(f'/_nicegui/{__version__}' + '/libraries/{key:path}')
  46. def _get_library(key: str) -> FileResponse:
  47. is_map = key.endswith('.map')
  48. dict_key = key[:-4] if is_map else key
  49. if dict_key in libraries:
  50. path = libraries[dict_key].path
  51. if is_map:
  52. path = path.with_name(path.name + '.map')
  53. if path.exists():
  54. headers = {'Cache-Control': 'public, max-age=3600'}
  55. return FileResponse(path, media_type='text/javascript', headers=headers)
  56. raise HTTPException(status_code=404, detail=f'library "{key}" not found')
  57. @app.get(f'/_nicegui/{__version__}' + '/components/{key:path}')
  58. def _get_component(key: str) -> FileResponse:
  59. if key in js_components and js_components[key].path.exists():
  60. headers = {'Cache-Control': 'public, max-age=3600'}
  61. return FileResponse(js_components[key].path, media_type='text/javascript', headers=headers)
  62. raise HTTPException(status_code=404, detail=f'component "{key}" not found')
  63. def _startup() -> None:
  64. """Handle the startup event."""
  65. # NOTE ping interval and timeout need to be lower than the reconnect timeout, but can't be too low
  66. sio.eio.ping_interval = max(app._run_config.reconnect_timeout * 0.8, 4) # pylint: disable=protected-access
  67. sio.eio.ping_timeout = max(app._run_config.reconnect_timeout * 0.4, 2) # pylint: disable=protected-access
  68. if not hasattr(app, '_run_config'):
  69. raise RuntimeError('\n\n'
  70. 'You must call ui.run() to start the server.\n'
  71. 'If ui.run() is behind a main guard\n'
  72. ' if __name__ == "__main__":\n'
  73. 'remove the guard or replace it with\n'
  74. ' if __name__ in {"__main__", "__mp_main__"}:\n'
  75. 'to allow for multiprocessing.')
  76. global_favicon = app._run_config.favicon # pylint: disable=protected-access
  77. if global_favicon:
  78. if helpers.is_file(global_favicon):
  79. app.add_route('/favicon.ico', lambda _: FileResponse(global_favicon)) # type: ignore
  80. else:
  81. app.add_route('/favicon.ico', lambda _: favicon.get_favicon_response())
  82. else:
  83. app.add_route('/favicon.ico', lambda _: FileResponse(Path(__file__).parent / 'static' / 'favicon.ico'))
  84. core.loop = asyncio.get_running_loop()
  85. app.start()
  86. background_tasks.create(binding.refresh_loop(), name='refresh bindings')
  87. background_tasks.create(outbox.loop(air.instance), name='send outbox')
  88. background_tasks.create(Client.prune_instances(), name='prune clients')
  89. background_tasks.create(Slot.prune_stacks(), name='prune slot stacks')
  90. air.connect()
  91. async def _shutdown() -> None:
  92. """Handle the shutdown event."""
  93. if app.native.main_window:
  94. app.native.main_window.signal_server_shutdown()
  95. app.stop()
  96. run.tear_down()
  97. air.disconnect()
  98. @app.exception_handler(404)
  99. async def _exception_handler_404(request: Request, exception: Exception) -> Response:
  100. log.warning(f'{request.url} not found')
  101. with Client(page('')) as client:
  102. error_content(404, exception)
  103. return client.build_response(request, 404)
  104. @app.exception_handler(Exception)
  105. async def _exception_handler_500(request: Request, exception: Exception) -> Response:
  106. log.exception(exception)
  107. with Client(page('')) as client:
  108. error_content(500, exception)
  109. return client.build_response(request, 500)
  110. @sio.on('handshake')
  111. async def _on_handshake(sid: str, client_id: str) -> bool:
  112. client = Client.instances.get(client_id)
  113. if not client:
  114. return False
  115. client.environ = sio.get_environ(sid)
  116. await sio.enter_room(sid, client.id)
  117. client.handle_handshake()
  118. return True
  119. @sio.on('disconnect')
  120. def _on_disconnect(sid: str) -> None:
  121. query_bytes: bytearray = sio.get_environ(sid)['asgi.scope']['query_string']
  122. query = urllib.parse.parse_qs(query_bytes.decode())
  123. client_id = query['client_id'][0]
  124. client = Client.instances.get(client_id)
  125. if client:
  126. client.handle_disconnect()
  127. @sio.on('event')
  128. def _on_event(_: str, msg: Dict) -> None:
  129. client = Client.instances.get(msg['client_id'])
  130. if not client or not client.has_socket_connection:
  131. return
  132. client.handle_event(msg)
  133. @sio.on('javascript_response')
  134. def _on_javascript_response(_: str, msg: Dict) -> None:
  135. client = Client.instances.get(msg['client_id'])
  136. if not client:
  137. return
  138. client.handle_javascript_response(msg)