浏览代码

move on_connect from ui.run() to separate method, hold connect, startup and shutdown tasks in globals module

Falko Schindler 2 年之前
父节点
当前提交
550df46622
共有 8 个文件被更改,包括 27 次插入25 次删除
  1. 0 1
      README.md
  2. 1 2
      nicegui/config.py
  3. 7 7
      nicegui/elements/page.py
  4. 4 1
      nicegui/globals.py
  5. 8 7
      nicegui/lifecycle.py
  6. 5 4
      nicegui/nicegui.py
  7. 1 2
      nicegui/run.py
  8. 1 1
      nicegui/ui.py

+ 0 - 1
README.md

@@ -80,7 +80,6 @@ You can call `ui.run()` with optional arguments:
 - `dark`: whether to use Quasar's dark mode (default: `False`, use `None` for "auto" mode)
 - `reload`: automatically reload the ui on file changes (default: `True`)
 - `show`: automatically open the ui in a browser tab (default: `True`)
-- `on_connect`: default function or coroutine which is called for each new client connection; the optional `request` argument provides session infos
 - `uvicorn_logging_level`: logging level for uvicorn server (default: `'warning'`)
 - `uvicorn_reload_dirs`: string with comma-separated list for directories to be monitored (default is current working directory only)
 - `uvicorn_reload_includes`: string with comma-separated list of glob-patterns which trigger reload on modification (default: `'.py'`)

+ 1 - 2
nicegui/config.py

@@ -2,7 +2,7 @@ import ast
 import inspect
 import os
 from dataclasses import dataclass
-from typing import Callable, Optional
+from typing import Optional
 
 from . import globals
 
@@ -17,7 +17,6 @@ class Config():
     dark: Optional[bool] = False
     reload: bool = True
     show: bool = True
-    on_connect: Optional[Callable] = None
     uvicorn_logging_level: str = 'warning'
     uvicorn_reload_dirs: str = '.'
     uvicorn_reload_includes: str = '*.py'

+ 7 - 7
nicegui/elements/page.py

@@ -8,7 +8,7 @@ import justpy as jp
 from pygments.formatters import HtmlFormatter
 from starlette.requests import Request
 
-from ..globals import config, page_stack, view_stack
+from ..globals import config, connect_handlers, page_stack, view_stack
 from ..helpers import is_coroutine
 
 
@@ -43,7 +43,7 @@ class Page(jp.QuasarPage):
         self.dark = dark if dark is not ... else config.dark
         self.tailwind = True  # use Tailwind classes instead of Quasars
         self.css = css
-        self.on_connect = on_connect or config.on_connect
+        self.on_connect = on_connect
 
         self.waiting_javascript_commands: dict[str, str] = {}
         self.on('result_ready', self.handle_javascript_result)
@@ -55,13 +55,13 @@ class Page(jp.QuasarPage):
         jp.Route(route, self._route_function)
 
     async def _route_function(self, request: Request):
-        if self.on_connect:
-            arg_count = len(inspect.signature(self.on_connect).parameters)
-            is_coro = is_coroutine(self.on_connect)
+        for connect_handler in connect_handlers + ([self.on_connect] if self.on_connect else []):
+            arg_count = len(inspect.signature(connect_handler).parameters)
+            is_coro = is_coroutine(connect_handler)
             if arg_count == 1:
-                await self.on_connect(request) if is_coro else self.on_connect(request)
+                await connect_handler(request) if is_coro else connect_handler(request)
             elif arg_count == 0:
-                await self.on_connect() if is_coro else self.on_connect()
+                await connect_handler() if is_coro else connect_handler()
             else:
                 raise ValueError(f'invalid number of arguments (0 or 1 allowed, got {arg_count})')
         return self

+ 4 - 1
nicegui/globals.py

@@ -2,7 +2,7 @@ from __future__ import annotations
 
 import asyncio
 import logging
-from typing import TYPE_CHECKING, List
+from typing import TYPE_CHECKING, Awaitable, Callable, List, Union
 
 if TYPE_CHECKING:
     import justpy as jp
@@ -17,3 +17,6 @@ page_stack: List['Page'] = []
 view_stack: List['jp.HTMLBaseComponent'] = []
 tasks: List[asyncio.tasks.Task] = []
 log: logging.Logger = logging.getLogger('nicegui')
+connect_handlers: List[Union[Callable, Awaitable]] = []
+startup_handlers: List[Union[Callable, Awaitable]] = []
+shutdown_handlers: List[Union[Callable, Awaitable]] = []

+ 8 - 7
nicegui/lifecycle.py

@@ -1,14 +1,15 @@
-from typing import Awaitable, Callable, List, Union
+from typing import Awaitable, Callable, Union
 
-startup_tasks: List[Union[Callable, Awaitable]] = []
+from .globals import connect_handlers, shutdown_handlers, startup_handlers
 
 
-def on_startup(self, task: Union[Callable, Awaitable]):
-    self.startup_tasks.append(task)
+def on_connect(self, handler: Union[Callable, Awaitable]):
+    connect_handlers.append(handler)
 
 
-shutdown_tasks: List[Union[Callable, Awaitable]] = []
+def on_startup(self, handler: Union[Callable, Awaitable]):
+    startup_handlers.append(handler)
 
 
-def on_shutdown(self, task: Union[Callable, Awaitable]):
-    self.shutdown_tasks.append(task)
+def on_shutdown(self, handler: Union[Callable, Awaitable]):
+    shutdown_handlers.append(handler)

+ 5 - 4
nicegui/nicegui.py

@@ -13,15 +13,16 @@ from .timer import Timer
 def startup():
     globals.tasks.extend(create_task(t.coro, name=t.name) for t in Timer.prepared_coroutines)
     Timer.prepared_coroutines.clear()
-    globals.tasks.extend(create_task(t, name='startup task') for t in Ui.startup_tasks if isinstance(t, Awaitable))
-    [safe_invoke(t) for t in Ui.startup_tasks if isinstance(t, Callable)]
+    globals.tasks.extend(create_task(t, name='startup task')
+                         for t in globals.startup_handlers if isinstance(t, Awaitable))
+    [safe_invoke(t) for t in globals.startup_handlers if isinstance(t, Callable)]
     jp.run_task(binding.loop())
 
 
 @jp.app.on_event('shutdown')
 def shutdown():
-    [create_task(t, name='shutdown task') for t in Ui.shutdown_tasks if isinstance(t, Awaitable)]
-    [safe_invoke(t) for t in Ui.shutdown_tasks if isinstance(t, Callable)]
+    [create_task(t, name='shutdown task') for t in globals.shutdown_handlers if isinstance(t, Awaitable)]
+    [safe_invoke(t) for t in globals.shutdown_handlers if isinstance(t, Callable)]
     [t.cancel() for t in globals.tasks]
 
 

+ 1 - 2
nicegui/run.py

@@ -2,7 +2,7 @@ import inspect
 import os
 import sys
 import webbrowser
-from typing import Callable, Optional
+from typing import Optional
 
 import uvicorn
 
@@ -34,7 +34,6 @@ def run(self, *,
         dark: Optional[bool] = False,
         reload: bool = True,
         show: bool = True,
-        on_connect: Optional[Callable] = None,
         uvicorn_logging_level: str = 'warning',
         uvicorn_reload_dirs: str = '.',
         uvicorn_reload_includes: str = '*.py',

+ 1 - 1
nicegui/ui.py

@@ -44,7 +44,7 @@ class Ui:
     from .elements.toggle import Toggle as toggle
     from .elements.tree import Tree as tree
     from .elements.upload import Upload as upload
-    from .lifecycle import on_shutdown, on_startup, shutdown_tasks, startup_tasks
+    from .lifecycle import on_connect, on_shutdown, on_startup
     from .routes import add_route, add_static_files, get
     from .timer import Timer as timer