瀏覽代碼

integrate ui.on_connect and ui.on_disconnect

Falko Schindler 2 年之前
父節點
當前提交
2ddf16f30b
共有 8 個文件被更改,包括 16 次插入14 次删除
  1. 4 0
      nicegui/client.py
  2. 1 1
      nicegui/events.py
  3. 3 3
      nicegui/functions/lifecycle.py
  4. 1 1
      nicegui/functions/timer.py
  5. 0 2
      nicegui/globals.py
  6. 4 0
      nicegui/nicegui.py
  7. 1 1
      nicegui/ui.py
  8. 2 6
      website/api_docs_and_examples.py

+ 4 - 0
nicegui/client.py

@@ -1,3 +1,4 @@
+from typing import Awaitable, List
 import asyncio
 import json
 import time
@@ -42,6 +43,9 @@ class Client:
 
         self.page = page
 
+        self.connect_handlers: List[Union[Callable, Awaitable]] = []
+        self.disconnect_handlers: List[Union[Callable, Awaitable]] = []
+
     @property
     def ip(self) -> Optional[str]:
         return self.environ.get('REMOTE_ADDR') if self.environ else None

+ 1 - 1
nicegui/events.py

@@ -6,8 +6,8 @@ from typing import TYPE_CHECKING, Any, Callable, List, Optional
 from . import globals
 from .async_updater import AsyncUpdater
 from .client import Client
+from .functions.lifecycle import on_startup
 from .helpers import is_coroutine
-from .lifecycle import on_startup
 from .task_logger import create_task
 
 if TYPE_CHECKING:

+ 3 - 3
nicegui/lifecycle.py → nicegui/functions/lifecycle.py

@@ -1,14 +1,14 @@
 from typing import Awaitable, Callable, Union
 
-from . import globals
+from .. import globals
 
 
 def on_connect(handler: Union[Callable, Awaitable]) -> None:
-    globals.connect_handlers.append(handler)
+    globals.get_client().connect_handlers.append(handler)
 
 
 def on_disconnect(handler: Union[Callable, Awaitable]) -> None:
-    globals.disconnect_handlers.append(handler)
+    globals.get_client().disconnect_handlers.append(handler)
 
 
 def on_startup(handler: Union[Callable, Awaitable]) -> None:

+ 1 - 1
nicegui/functions/timer.py

@@ -7,8 +7,8 @@ from .. import globals
 from ..async_updater import AsyncUpdater
 from ..binding import BindableProperty
 from ..helpers import is_coroutine
-from ..lifecycle import on_startup
 from ..task_logger import create_task
+from .lifecycle import on_startup
 
 
 class Timer:

+ 0 - 2
nicegui/globals.py

@@ -44,8 +44,6 @@ page_routes: Dict[Callable, str] = {}
 favicons: Dict[str, Optional[str]] = {}
 tasks: List[asyncio.tasks.Task] = []
 
-connect_handlers: List[Union[Callable, Awaitable]] = []
-disconnect_handlers: List[Union[Callable, Awaitable]] = []
 startup_handlers: List[Union[Callable, Awaitable]] = []
 shutdown_handlers: List[Union[Callable, Awaitable]] = []
 

+ 4 - 0
nicegui/nicegui.py

@@ -81,6 +81,8 @@ async def handle_connect(sid: str, _) -> None:
         return
     client.environ = sio.get_environ(sid)
     sio.enter_room(sid, str(client.id))
+    with client:
+        [safe_invoke(t) for t in client.connect_handlers]
 
 
 @sio.on('disconnect')
@@ -90,6 +92,8 @@ async def handle_disconnect(sid: str) -> None:
         return
     if not client.shared:
         del globals.clients[client.id]
+    with client:
+        [safe_invoke(t) for t in client.disconnect_handlers]
 
 
 @sio.on('event')

+ 1 - 1
nicegui/ui.py

@@ -44,12 +44,12 @@ from .elements.tree import Tree as tree
 from .elements.upload import Upload as upload
 from .functions.html import add_body_html, add_head_html
 from .functions.javascript import run_javascript
+from .functions.lifecycle import on_connect, on_disconnect, on_shutdown, on_startup, shutdown
 from .functions.notify import notify
 from .functions.open import open
 from .functions.static_files import add_static_files
 from .functions.timer import Timer as timer
 from .functions.update import update
-from .lifecycle import on_connect, on_disconnect, on_shutdown, on_startup, shutdown
 from .page import page
 from .page_layout import Footer as footer
 from .page_layout import Header as header

+ 2 - 6
website/api_docs_and_examples.py

@@ -443,9 +443,8 @@ You can run a function or coroutine as a parallel task by passing it to one of t
 - `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
 
 When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
-''', skip=True)
+''')
     def lifecycle_example():
-        global countdown
         import asyncio
 
         l = ui.label()
@@ -455,7 +454,7 @@ When NiceGUI is shut down or restarted, the startup tasks will be automatically
                 l.text = f'{i}...' if i else 'Take-off!'
                 await asyncio.sleep(1)
 
-        # ui.on_connect(countdown)
+        ui.on_connect(countdown)
 
     @example(ui.timer)
     def timer_example():
@@ -754,6 +753,3 @@ This will make `ui.plot` and `ui.line_plot` unavailable.
         if line_checkbox.value:
             ui.timer(10.0, turn_off, once=True)
     line_checkbox.on('update:model-value', handle_change)
-
-    # HACK: start countdown here to avoid using global lifecycle hook
-    # create_task(countdown(), name='countdown')