Skip to content

Commit

Permalink
optional client param for ui.on_*connect
Browse files Browse the repository at this point in the history
  • Loading branch information
rodja committed Jan 8, 2023
1 parent ec6c12a commit bc7e3f0
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 6 deletions.
5 changes: 3 additions & 2 deletions nicegui/helpers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import asyncio
import functools
import inspect
from contextlib import nullcontext
from typing import Any, Awaitable, Callable, List, Optional, Union

Expand All @@ -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():
Expand All @@ -23,7 +24,7 @@ async def func_with_client():
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():
Expand Down
4 changes: 2 additions & 2 deletions nicegui/nicegui.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand All @@ -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')
Expand Down
4 changes: 2 additions & 2 deletions website/reference.py
Original file line number Diff line number Diff line change
Expand Up @@ -486,8 +486,8 @@ def colors_example():
- `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)
Expand Down

0 comments on commit bc7e3f0

Please sign in to comment.