nicegui.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. import asyncio
  2. import os
  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 nicegui import json
  13. from nicegui.json import NiceGUIJSONResponse
  14. from . import __version__, background_tasks, binding, favicon, globals, outbox
  15. from .app import App
  16. from .client import Client
  17. from .dependencies import js_components, js_dependencies
  18. from .element import Element
  19. from .error import error_content
  20. from .helpers import get_all_ips, is_file, safe_invoke
  21. from .page import page
  22. globals.app = app = App(default_response_class=NiceGUIJSONResponse)
  23. # NOTE we use custom json module which wraps orjson
  24. socket_manager = SocketManager(app=app, mount_location='/_nicegui_ws/', json=json)
  25. globals.sio = sio = socket_manager._sio
  26. app.add_middleware(GZipMiddleware)
  27. static_files = StaticFiles(
  28. directory=(Path(__file__).parent / 'static').resolve(),
  29. follow_symlink=True,
  30. )
  31. app.mount(f'/_nicegui/{__version__}/static', static_files, name='static')
  32. globals.index_client = Client(page('/'), shared=True).__enter__()
  33. @app.get('/')
  34. def index(request: Request) -> Response:
  35. return globals.index_client.build_response(request)
  36. @app.get(f'/_nicegui/{__version__}' + '/dependencies/{id}/{name}')
  37. def get_dependencies(id: int, name: str):
  38. if id in js_dependencies and js_dependencies[id].path.exists() and js_dependencies[id].path.name == name:
  39. return FileResponse(js_dependencies[id].path, media_type='text/javascript')
  40. raise HTTPException(status_code=404, detail=f'dependency "{name}" with ID {id} not found')
  41. @app.get(f'/_nicegui/{__version__}' + '/components/{name}')
  42. def get_components(name: str):
  43. return FileResponse(js_components[name].path, media_type='text/javascript')
  44. @app.on_event('startup')
  45. def handle_startup(with_welcome_message: bool = True) -> None:
  46. if not globals.ui_run_has_been_called:
  47. raise RuntimeError('\n\n'
  48. 'You must call ui.run() to start the server.\n'
  49. 'If ui.run() is behind a main guard\n'
  50. ' if __name__ == "__main__":\n'
  51. 'remove the guard or replace it with\n'
  52. ' if __name__ in {"__main__", "__mp_main__"}:\n'
  53. 'to allow for multiprocessing.')
  54. if globals.favicon:
  55. if is_file(globals.favicon):
  56. globals.app.add_route('/favicon.ico', lambda _: FileResponse(globals.favicon))
  57. else:
  58. globals.app.add_route('/favicon.ico', lambda _: favicon.get_favicon_response())
  59. else:
  60. globals.app.add_route('/favicon.ico', lambda _: FileResponse(Path(__file__).parent / 'static' / 'favicon.ico'))
  61. globals.state = globals.State.STARTING
  62. globals.loop = asyncio.get_running_loop()
  63. with globals.index_client:
  64. for t in globals.startup_handlers:
  65. safe_invoke(t)
  66. background_tasks.create(binding.loop())
  67. background_tasks.create(outbox.loop())
  68. background_tasks.create(prune_clients())
  69. background_tasks.create(prune_slot_stacks())
  70. globals.state = globals.State.STARTED
  71. if with_welcome_message:
  72. print_welcome_message()
  73. def print_welcome_message():
  74. host = os.environ['NICEGUI_HOST']
  75. port = os.environ['NICEGUI_PORT']
  76. ips = set(get_all_ips() if host == '0.0.0.0' else [])
  77. ips.discard('127.0.0.1')
  78. addresses = [(f'http://{ip}:{port}' if port != '80' else f'http://{ip}') for ip in ['localhost'] + sorted(ips)]
  79. if len(addresses) >= 2:
  80. addresses[-1] = 'and ' + addresses[-1]
  81. print(f'NiceGUI ready to go on {", ".join(addresses)}', flush=True)
  82. @app.on_event('shutdown')
  83. async def handle_shutdown() -> None:
  84. if app.native.main_window:
  85. app.native.main_window.signal_server_shutdown()
  86. globals.state = globals.State.STOPPING
  87. with globals.index_client:
  88. for t in globals.shutdown_handlers:
  89. safe_invoke(t)
  90. globals.state = globals.State.STOPPED
  91. @app.exception_handler(404)
  92. async def exception_handler_404(request: Request, exception: Exception) -> Response:
  93. globals.log.warning(f'{request.url} not found')
  94. with Client(page('')) as client:
  95. error_content(404, exception)
  96. return client.build_response(request, 404)
  97. @app.exception_handler(Exception)
  98. async def exception_handler_500(request: Request, exception: Exception) -> Response:
  99. globals.log.exception(exception)
  100. with Client(page('')) as client:
  101. error_content(500, exception)
  102. return client.build_response(request, 500)
  103. @sio.on('handshake')
  104. def handle_handshake(sid: str) -> bool:
  105. client = get_client(sid)
  106. if not client:
  107. return False
  108. client.environ = sio.get_environ(sid)
  109. sio.enter_room(sid, client.id)
  110. for t in client.connect_handlers:
  111. safe_invoke(t, client)
  112. for t in globals.connect_handlers:
  113. safe_invoke(t, client)
  114. return True
  115. @sio.on('disconnect')
  116. def handle_disconnect(sid: str) -> None:
  117. client = get_client(sid)
  118. if not client:
  119. return
  120. if not client.shared:
  121. delete_client(client.id)
  122. for t in client.disconnect_handlers:
  123. safe_invoke(t, client)
  124. for t in globals.disconnect_handlers:
  125. safe_invoke(t, client)
  126. @sio.on('event')
  127. def handle_event(sid: str, msg: Dict) -> None:
  128. client = get_client(sid)
  129. if not client or not client.has_socket_connection:
  130. return
  131. with client:
  132. sender = client.elements.get(msg['id'])
  133. if sender:
  134. sender._handle_event(msg)
  135. @sio.on('javascript_response')
  136. def handle_javascript_response(sid: str, msg: Dict) -> None:
  137. client = get_client(sid)
  138. if not client:
  139. return
  140. client.waiting_javascript_commands[msg['request_id']] = msg['result']
  141. def get_client(sid: str) -> Optional[Client]:
  142. query_bytes: bytearray = sio.get_environ(sid)['asgi.scope']['query_string']
  143. query = urllib.parse.parse_qs(query_bytes.decode())
  144. client_id = query['client_id'][0]
  145. return globals.clients.get(client_id)
  146. async def prune_clients() -> None:
  147. while True:
  148. stale = [
  149. id
  150. for id, client in globals.clients.items()
  151. if not client.shared and not client.has_socket_connection and client.created < time.time() - 60.0
  152. ]
  153. for id in stale:
  154. delete_client(id)
  155. await asyncio.sleep(10)
  156. async def prune_slot_stacks() -> None:
  157. while True:
  158. running = [
  159. id(task)
  160. for task in asyncio.tasks.all_tasks()
  161. if not task.done() and not task.cancelled()
  162. ]
  163. stale = [
  164. id_
  165. for id_ in globals.slot_stacks
  166. if id_ not in running
  167. ]
  168. for id_ in stale:
  169. del globals.slot_stacks[id_]
  170. await asyncio.sleep(10)
  171. def delete_client(id: str) -> None:
  172. binding.remove(list(globals.clients[id].elements.values()), Element)
  173. for element in globals.clients[id].elements.values():
  174. element.delete()
  175. del globals.clients[id]