ui_run.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. import multiprocessing
  2. import os
  3. import sys
  4. from pathlib import Path
  5. from typing import Any, List, Literal, Optional, Tuple, Union
  6. import __main__
  7. from starlette.routing import Route
  8. from uvicorn.main import STARTUP_FAILURE
  9. from uvicorn.supervisors import ChangeReload, Multiprocess
  10. from . import core, helpers
  11. from . import native as native_module
  12. from .air import Air
  13. from .client import Client
  14. from .language import Language
  15. from .logging import log
  16. from .server import CustomServerConfig, Server
  17. APP_IMPORT_STRING = 'nicegui:app'
  18. def run(*,
  19. host: Optional[str] = None,
  20. port: Optional[int] = None,
  21. title: str = 'NiceGUI',
  22. viewport: str = 'width=device-width, initial-scale=1',
  23. favicon: Optional[Union[str, Path]] = None,
  24. dark: Optional[bool] = False,
  25. language: Language = 'en-US',
  26. binding_refresh_interval: float = 0.1,
  27. reconnect_timeout: float = 3.0,
  28. show: bool = True,
  29. on_air: Optional[Union[str, Literal[True]]] = None,
  30. native: bool = False,
  31. window_size: Optional[Tuple[int, int]] = None,
  32. fullscreen: bool = False,
  33. frameless: bool = False,
  34. reload: bool = True,
  35. uvicorn_logging_level: str = 'warning',
  36. uvicorn_reload_dirs: str = '.',
  37. uvicorn_reload_includes: str = '*.py',
  38. uvicorn_reload_excludes: str = '.*, .py[cod], .sw.*, ~*',
  39. tailwind: bool = True,
  40. prod_js: bool = True,
  41. endpoint_documentation: Literal['none', 'internal', 'page', 'all'] = 'none',
  42. storage_secret: Optional[str] = None,
  43. show_welcome_message: bool = True,
  44. **kwargs: Any,
  45. ) -> None:
  46. """ui.run
  47. You can call `ui.run()` with optional arguments.
  48. Most of them only apply after stopping and fully restarting the app and do not apply with auto-reloading.
  49. :param host: start server with this host (defaults to `'127.0.0.1` in native mode, otherwise `'0.0.0.0'`)
  50. :param port: use this port (default: 8080 in normal mode, and an automatically determined open port in native mode)
  51. :param title: page title (default: `'NiceGUI'`, can be overwritten per page)
  52. :param viewport: page meta viewport content (default: `'width=device-width, initial-scale=1'`, can be overwritten per page)
  53. :param favicon: relative filepath, absolute URL to a favicon (default: `None`, NiceGUI icon will be used) or emoji (e.g. `'🚀'`, works for most browsers)
  54. :param dark: whether to use Quasar's dark mode (default: `False`, use `None` for "auto" mode)
  55. :param language: language for Quasar elements (default: `'en-US'`)
  56. :param binding_refresh_interval: time between binding updates (default: `0.1` seconds, bigger is more CPU friendly)
  57. :param reconnect_timeout: maximum time the server waits for the browser to reconnect (default: 3.0 seconds)
  58. :param show: automatically open the UI in a browser tab (default: `True`)
  59. :param on_air: tech preview: `allows temporary remote access <https://nicegui.io/documentation/section_configuration_deployment#nicegui_on_air>`_ if set to `True` (default: disabled)
  60. :param native: open the UI in a native window of size 800x600 (default: `False`, deactivates `show`, automatically finds an open port)
  61. :param window_size: open the UI in a native window with the provided size (e.g. `(1024, 786)`, default: `None`, also activates `native`)
  62. :param fullscreen: open the UI in a fullscreen window (default: `False`, also activates `native`)
  63. :param frameless: open the UI in a frameless window (default: `False`, also activates `native`)
  64. :param reload: automatically reload the UI on file changes (default: `True`)
  65. :param uvicorn_logging_level: logging level for uvicorn server (default: `'warning'`)
  66. :param uvicorn_reload_dirs: string with comma-separated list for directories to be monitored (default is current working directory only)
  67. :param uvicorn_reload_includes: string with comma-separated list of glob-patterns which trigger reload on modification (default: `'*.py'`)
  68. :param uvicorn_reload_excludes: string with comma-separated list of glob-patterns which should be ignored for reload (default: `'.*, .py[cod], .sw.*, ~*'`)
  69. :param tailwind: whether to use Tailwind (experimental, default: `True`)
  70. :param prod_js: whether to use the production version of Vue and Quasar dependencies (default: `True`)
  71. :param endpoint_documentation: control what endpoints appear in the autogenerated OpenAPI docs (default: 'none', options: 'none', 'internal', 'page', 'all')
  72. :param storage_secret: secret key for browser-based storage (default: `None`, a value is required to enable ui.storage.individual and ui.storage.browser)
  73. :param show_welcome_message: whether to show the welcome message (default: `True`)
  74. :param kwargs: additional keyword arguments are passed to `uvicorn.run`
  75. """
  76. core.app.config.add_run_config(
  77. reload=reload,
  78. title=title,
  79. viewport=viewport,
  80. favicon=favicon,
  81. dark=dark,
  82. language=language,
  83. binding_refresh_interval=binding_refresh_interval,
  84. reconnect_timeout=reconnect_timeout,
  85. tailwind=tailwind,
  86. prod_js=prod_js,
  87. show_welcome_message=show_welcome_message,
  88. )
  89. core.app.config.endpoint_documentation = endpoint_documentation
  90. for route in core.app.routes:
  91. if not isinstance(route, Route):
  92. continue
  93. if route.path.startswith('/_nicegui') and hasattr(route, 'methods'):
  94. route.include_in_schema = endpoint_documentation in {'internal', 'all'}
  95. if route.path == '/' or route.path in Client.page_routes.values():
  96. route.include_in_schema = endpoint_documentation in {'page', 'all'}
  97. if on_air:
  98. core.air = Air('' if on_air is True else on_air)
  99. if multiprocessing.current_process().name != 'MainProcess':
  100. return
  101. if reload and not hasattr(__main__, '__file__'):
  102. log.warning('disabling auto-reloading because is is only supported when running from a file')
  103. core.app.config.reload = reload = False
  104. if fullscreen:
  105. native = True
  106. if frameless:
  107. native = True
  108. if window_size:
  109. native = True
  110. if native:
  111. show = False
  112. host = host or '127.0.0.1'
  113. port = port or native_module.find_open_port()
  114. width, height = window_size or (800, 600)
  115. native_module.activate(host, port, title, width, height, fullscreen, frameless)
  116. else:
  117. port = port or 8080
  118. host = host or '0.0.0.0'
  119. assert host is not None
  120. assert port is not None
  121. # NOTE: We save host and port in environment variables so the subprocess started in reload mode can access them.
  122. os.environ['NICEGUI_HOST'] = host
  123. os.environ['NICEGUI_PORT'] = str(port)
  124. if show:
  125. helpers.schedule_browser(host, port)
  126. def split_args(args: str) -> List[str]:
  127. return [a.strip() for a in args.split(',')]
  128. if kwargs.get('workers', 1) > 1:
  129. raise ValueError('NiceGUI does not support multiple workers yet.')
  130. # NOTE: The following lines are basically a copy of `uvicorn.run`, but keep a reference to the `server`.
  131. config = CustomServerConfig(
  132. APP_IMPORT_STRING if reload else core.app,
  133. host=host,
  134. port=port,
  135. reload=reload,
  136. reload_includes=split_args(uvicorn_reload_includes) if reload else None,
  137. reload_excludes=split_args(uvicorn_reload_excludes) if reload else None,
  138. reload_dirs=split_args(uvicorn_reload_dirs) if reload else None,
  139. log_level=uvicorn_logging_level,
  140. **kwargs,
  141. )
  142. config.storage_secret = storage_secret
  143. config.method_queue = native_module.method_queue if native else None
  144. config.response_queue = native_module.response_queue if native else None
  145. Server.create_singleton(config)
  146. if (reload or config.workers > 1) and not isinstance(config.app, str):
  147. log.warning('You must pass the application as an import string to enable "reload" or "workers".')
  148. sys.exit(1)
  149. if config.should_reload:
  150. sock = config.bind_socket()
  151. ChangeReload(config, target=Server.instance.run, sockets=[sock]).run()
  152. elif config.workers > 1:
  153. sock = config.bind_socket()
  154. Multiprocess(config, target=Server.instance.run, sockets=[sock]).run()
  155. else:
  156. Server.instance.run()
  157. if config.uds:
  158. os.remove(config.uds) # pragma: py-win32
  159. if not Server.instance.started and not config.should_reload and config.workers == 1:
  160. sys.exit(STARTUP_FAILURE)