Sfoglia il codice sorgente

rename app configs

Falko Schindler 1 anno fa
parent
commit
086670a605
10 ha cambiato i file con 42 aggiunte e 37 eliminazioni
  1. 2 2
      main.py
  2. 4 4
      nicegui/app.py
  3. 2 2
      nicegui/app_config.py
  4. 1 1
      nicegui/binding.py
  5. 10 7
      nicegui/client.py
  6. 5 4
      nicegui/favicon.py
  7. 7 6
      nicegui/nicegui.py
  8. 5 5
      nicegui/page.py
  9. 4 4
      nicegui/ui_run.py
  10. 2 2
      nicegui/ui_run_with.py

+ 2 - 2
main.py

@@ -65,8 +65,8 @@ async def redirect_reference_to_documentation(request: Request,
 
 # NOTE In our global fly.io deployment we need to make sure that we connect back to the same instance.
 fly_instance_id = os.environ.get('FLY_ALLOC_ID', 'local').split('-')[0]
-app.extra_config.socket_io_js_extra_headers['fly-force-instance-id'] = fly_instance_id  # for HTTP long polling
-app.extra_config.socket_io_js_query_params['fly_instance_id'] = fly_instance_id  # for websocket (FlyReplayMiddleware)
+app.config.socket_io_js_extra_headers['fly-force-instance-id'] = fly_instance_id  # for HTTP long polling
+app.config.socket_io_js_query_params['fly_instance_id'] = fly_instance_id  # for websocket (FlyReplayMiddleware)
 
 
 class FlyReplayMiddleware(BaseHTTPMiddleware):

+ 4 - 4
nicegui/app.py

@@ -8,7 +8,7 @@ from fastapi.responses import FileResponse, StreamingResponse
 from fastapi.staticfiles import StaticFiles
 
 from . import background_tasks, core, helpers
-from .app_config import AppConfig, ExtraConfig
+from .app_config import AppConfig, RunConfig
 from .client import Client
 from .logging import log
 from .native import NativeConfig
@@ -32,8 +32,8 @@ class App(FastAPI):
         self.storage = Storage()
         self.urls = ObservableSet()
         self._state: State = State.STOPPED
-        self.config: AppConfig
-        self.extra_config = ExtraConfig()
+        self._run_config: RunConfig
+        self.config = AppConfig()
 
         self._startup_handlers: List[Union[Callable[..., Any], Awaitable]] = []
         self._shutdown_handlers: List[Union[Callable[..., Any], Awaitable]] = []
@@ -125,7 +125,7 @@ class App(FastAPI):
         This will programmatically stop the server.
         Only possible when auto-reload is disabled.
         """
-        if core.app.config.reload:
+        if core.app._run_config.reload:  # pylint: disable=protected-access
             raise RuntimeError('calling shutdown() is not supported when auto-reload is enabled')
         if self.native.main_window:
             self.native.main_window.destroy()

+ 2 - 2
nicegui/app_config.py

@@ -7,7 +7,7 @@ from .language import Language
 
 
 @dataclass(**KWONLY_SLOTS)
-class AppConfig:
+class RunConfig:
     reload: bool
     title: str
     viewport: str
@@ -21,7 +21,7 @@ class AppConfig:
 
 
 @dataclass(**KWONLY_SLOTS)
-class ExtraConfig:
+class AppConfig:
     endpoint_documentation: Literal['none', 'internal', 'page', 'all'] = 'none'
     socket_io_js_query_params: Dict = field(default_factory=dict)
     socket_io_js_extra_headers: Dict = field(default_factory=dict)

+ 1 - 1
nicegui/binding.py

@@ -37,7 +37,7 @@ async def refresh_loop() -> None:
     """Refresh all bindings in an endless loop."""
     while True:
         _refresh_step()
-        await asyncio.sleep(core.app.config.binding_refresh_interval)
+        await asyncio.sleep(core.app._run_config.binding_refresh_interval)  # pylint: disable=protected-access
 
 
 def _refresh_step() -> None:

+ 10 - 7
nicegui/client.py

@@ -97,7 +97,7 @@ class Client:
         elements = json.dumps({
             id: element._to_dict() for id, element in self.elements.items()  # pylint: disable=protected-access
         })
-        socket_io_js_query_params = {**core.app.extra_config.socket_io_js_query_params, 'client_id': self.id}
+        socket_io_js_query_params = {**core.app.config.socket_io_js_query_params, 'client_id': self.id}
         vue_html, vue_styles, vue_scripts, imports, js_imports = generate_resources(prefix, self.elements.values())
         return templates.TemplateResponse('index.html', {
             'request': request,
@@ -111,18 +111,18 @@ class Client:
             'vue_scripts': '\n'.join(vue_scripts),
             'imports': json.dumps(imports),
             'js_imports': '\n'.join(js_imports),
-            'quasar_config': json.dumps(core.app.extra_config.quasar_config),
+            'quasar_config': json.dumps(core.app.config.quasar_config),
             'title': self.page.resolve_title(),
             'viewport': self.page.resolve_viewport(),
             'favicon_url': get_favicon_url(self.page, prefix),
             'dark': str(self.page.resolve_dark()),
             'language': self.page.resolve_language(),
             'prefix': prefix,
-            'tailwind': core.app.config.tailwind,
-            'prod_js': core.app.config.prod_js,
+            'tailwind': core.app._run_config.tailwind,  # pylint: disable=protected-access
+            'prod_js': core.app._run_config.prod_js,  # pylint: disable=protected-access
             'socket_io_js_query_params': socket_io_js_query_params,
-            'socket_io_js_extra_headers': core.app.extra_config.socket_io_js_extra_headers,
-            'socket_io_js_transports': core.app.extra_config.socket_io_js_transports,
+            'socket_io_js_extra_headers': core.app.config.socket_io_js_extra_headers,
+            'socket_io_js_transports': core.app.config.socket_io_js_transports,
         }, status_code, {'Cache-Control': 'no-store', 'X-NiceGUI-Content': 'page'})
 
     async def connected(self, timeout: float = 3.0, check_interval: float = 0.1) -> None:
@@ -208,7 +208,10 @@ class Client:
     def handle_disconnect(self) -> None:
         """Wait for the browser to reconnect; invoke disconnect handlers if it doesn't."""
         async def handle_disconnect() -> None:
-            delay = self.page.reconnect_timeout if self.page.reconnect_timeout is not None else core.app.config.reconnect_timeout
+            if self.page.reconnect_timeout is not None:
+                delay = self.page.reconnect_timeout
+            else:
+                delay = core.app._run_config.reconnect_timeout  # pylint: disable=protected-access
             await asyncio.sleep(delay)
             if not self.shared:
                 self.delete()

+ 5 - 4
nicegui/favicon.py

@@ -25,7 +25,7 @@ def create_favicon_route(path: str, favicon: Optional[Union[str, Path]]) -> None
 
 def get_favicon_url(page: page, prefix: str) -> str:
     """Return the URL of the favicon for a given page."""
-    favicon = page.favicon or core.app.config.favicon
+    favicon = page.favicon or core.app._run_config.favicon  # pylint: disable=protected-access
     if not favicon:
         return f'{prefix}/_nicegui/{__version__}/static/favicon.ico'
 
@@ -46,9 +46,10 @@ def get_favicon_url(page: page, prefix: str) -> str:
 
 def get_favicon_response() -> Response:
     """Return the FastAPI response for the global favicon."""
-    if not core.app.config.favicon:
-        raise ValueError(f'invalid favicon: {core.app.config.favicon}')
-    favicon = str(core.app.config.favicon).strip()
+    global_favicon = core.app._run_config.favicon  # pylint: disable=protected-access
+    if not global_favicon:
+        raise ValueError(f'invalid favicon: {global_favicon}')
+    favicon = str(global_favicon).strip()
 
     if _is_svg(favicon):
         return Response(favicon, media_type='image/svg+xml')

+ 7 - 6
nicegui/nicegui.py

@@ -72,9 +72,9 @@ def _get_component(key: str) -> FileResponse:
 def handle_startup(with_welcome_message: bool = True) -> None:
     """Handle the startup event."""
     # NOTE ping interval and timeout need to be lower than the reconnect timeout, but can't be too low
-    sio.eio.ping_interval = max(app.config.reconnect_timeout * 0.8, 4)
-    sio.eio.ping_timeout = max(app.config.reconnect_timeout * 0.4, 2)
-    if not hasattr(app, 'config'):
+    sio.eio.ping_interval = max(app._run_config.reconnect_timeout * 0.8, 4)  # pylint: disable=protected-access
+    sio.eio.ping_timeout = max(app._run_config.reconnect_timeout * 0.4, 2)  # pylint: disable=protected-access
+    if not hasattr(app, '_run_config'):
         raise RuntimeError('\n\n'
                            'You must call ui.run() to start the server.\n'
                            'If ui.run() is behind a main guard\n'
@@ -82,9 +82,10 @@ def handle_startup(with_welcome_message: bool = True) -> None:
                            'remove the guard or replace it with\n'
                            '   if __name__ in {"__main__", "__mp_main__"}:\n'
                            'to allow for multiprocessing.')
-    if app.config.favicon:
-        if helpers.is_file(app.config.favicon):
-            app.add_route('/favicon.ico', lambda _: FileResponse(app.config.favicon))  # type: ignore
+    global_favicon = app._run_config.favicon  # pylint: disable=protected-access
+    if global_favicon:
+        if helpers.is_file(global_favicon):
+            app.add_route('/favicon.ico', lambda _: FileResponse(global_favicon))  # type: ignore
         else:
             app.add_route('/favicon.ico', lambda _: favicon.get_favicon_response())
     else:

+ 5 - 5
nicegui/page.py

@@ -69,19 +69,19 @@ class page:
 
     def resolve_title(self) -> str:
         """Return the title of the page."""
-        return self.title if self.title is not None else core.app.config.title
+        return self.title if self.title is not None else core.app._run_config.title  # pylint: disable=protected-access
 
     def resolve_viewport(self) -> str:
         """Return the viewport of the page."""
-        return self.viewport if self.viewport is not None else core.app.config.viewport
+        return self.viewport if self.viewport is not None else core.app._run_config.viewport  # pylint: disable=protected-access
 
     def resolve_dark(self) -> Optional[bool]:
         """Return whether the page should use dark mode."""
-        return self.dark if self.dark is not ... else core.app.config.dark
+        return self.dark if self.dark is not ... else core.app._run_config.dark  # pylint: disable=protected-access
 
     def resolve_language(self) -> Optional[str]:
         """Return the language of the page."""
-        return self.language if self.language is not ... else core.app.config.language
+        return self.language if self.language is not ... else core.app._run_config.language  # pylint: disable=protected-access
 
     def __call__(self, func: Callable[..., Any]) -> Callable[..., Any]:
         core.app.remove_route(self.path)  # NOTE make sure only the latest route definition is used
@@ -119,7 +119,7 @@ class page:
         decorated.__signature__ = inspect.Signature(parameters)  # type: ignore
 
         if 'include_in_schema' not in self.kwargs:
-            self.kwargs['include_in_schema'] = core.app.extra_config.endpoint_documentation in {'page', 'all'}
+            self.kwargs['include_in_schema'] = core.app.config.endpoint_documentation in {'page', 'all'}
 
         self.api_router.get(self._path, **self.kwargs)(decorated)
         Client.page_routes[func] = self.path

+ 4 - 4
nicegui/ui_run.py

@@ -11,7 +11,7 @@ from uvicorn.supervisors import ChangeReload, Multiprocess
 
 from . import air, core, helpers
 from . import native as native_module
-from .app_config import AppConfig
+from .app_config import RunConfig
 from .client import Client
 from .language import Language
 from .logging import log
@@ -77,7 +77,7 @@ def run(*,
     :param storage_secret: secret key for browser-based storage (default: `None`, a value is required to enable ui.storage.individual and ui.storage.browser)
     :param kwargs: additional keyword arguments are passed to `uvicorn.run`    
     """
-    core.app.config = AppConfig(
+    core.app._run_config = RunConfig(  # pylint: disable=protected-access
         reload=reload,
         title=title,
         viewport=viewport,
@@ -89,7 +89,7 @@ def run(*,
         tailwind=tailwind,
         prod_js=prod_js,
     )
-    core.app.extra_config.endpoint_documentation = endpoint_documentation
+    core.app.config.endpoint_documentation = endpoint_documentation
 
     for route in core.app.routes:
         if not isinstance(route, Route):
@@ -107,7 +107,7 @@ def run(*,
 
     if reload and not hasattr(__main__, '__file__'):
         log.warning('auto-reloading is only supported when running from a file')
-        core.app.config.reload = reload = False
+        core.app._run_config.reload = reload = False  # pylint: disable=protected-access
 
     if fullscreen:
         native = True

+ 2 - 2
nicegui/ui_run_with.py

@@ -4,7 +4,7 @@ from typing import Optional, Union
 from fastapi import FastAPI
 
 from . import core, storage
-from .app_config import AppConfig
+from .app_config import RunConfig
 from .language import Language
 from .nicegui import handle_shutdown, handle_startup
 
@@ -38,7 +38,7 @@ def run_with(
     :param prod_js: whether to use the production version of Vue and Quasar dependencies (default: `True`)
     :param storage_secret: secret key for browser-based storage (default: `None`, a value is required to enable ui.storage.individual and ui.storage.browser)
     """
-    core.app.config = AppConfig(
+    core.app._run_config = RunConfig(  # pylint: disable=protected-access
         reload=False,
         title=title,
         viewport=viewport,