ソースを参照

optional client param for ui.on_*connect

Rodja Trappe 2 年 前
コミット
bc7e3f0978
3 ファイル変更7 行追加6 行削除
  1. 3 2
      nicegui/helpers.py
  2. 2 2
      nicegui/nicegui.py
  3. 2 2
      website/reference.py

+ 3 - 2
nicegui/helpers.py

@@ -1,5 +1,6 @@
 import asyncio
 import functools
+import inspect
 from contextlib import nullcontext
 from typing import Any, Awaitable, Callable, List, Optional, Union
 
@@ -14,7 +15,7 @@ def is_coroutine(object: Any) -> bool:
     return asyncio.iscoroutinefunction(object)
 
 
-def safe_invoke(func: Union[Callable, Awaitable], client: Optional[Client] = None, *args: List[Any]) -> None:
+def safe_invoke(func: Union[Callable, Awaitable], client: Optional[Client] = None) -> None:
     try:
         if isinstance(func, Awaitable):
             async def func_with_client():
@@ -23,7 +24,7 @@ def safe_invoke(func: Union[Callable, Awaitable], client: Optional[Client] = Non
             create_task(func_with_client())
         else:
             with client or nullcontext():
-                result = func(*args)
+                result = func(client) if len(inspect.signature(func).parameters) == 1 and client is not None else func()
             if isinstance(result, Awaitable):
                 async def result_with_client():
                     with client or nullcontext():

+ 2 - 2
nicegui/nicegui.py

@@ -95,7 +95,7 @@ async def handle_handshake(sid: str) -> bool:
     for t in client.connect_handlers:
         safe_invoke(t, client)
     for t in globals.connect_handlers:
-        safe_invoke(t, client, client)
+        safe_invoke(t, client)
     return True
 
 
@@ -109,7 +109,7 @@ async def handle_disconnect(sid: str) -> None:
     for t in client.disconnect_handlers:
         safe_invoke(t, client)
     for t in globals.disconnect_handlers:
-        safe_invoke(t, client, client)
+        safe_invoke(t, client)
 
 
 @sio.on('event')

+ 2 - 2
website/reference.py

@@ -486,8 +486,8 @@ You can run a function or coroutine as a parallel task by passing it to one of t
 
 - `ui.on_startup`: Called when NiceGUI is started or restarted.
 - `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
-- `ui.on_connect`: Called for each client which connects. (nicegui.Client is passed as argument)
-- `ui.on_disconnect`: Called for each client which disconnects. (nicegui.Client is passed as argument)
+- `ui.on_connect`: Called for each client which connects. (nicegui.Client is passed as optional argument)
+- `ui.on_disconnect`: Called for each client which disconnects. (nicegui.Client is passed as optional argument)
 
 When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
 ''', immediate=True)