浏览代码

warn if ui.open is used before client is connected

Rodja Trappe 1 年之前
父节点
当前提交
fcce033cbb
共有 2 个文件被更改,包括 8 次插入4 次删除
  1. 3 3
      nicegui/client.py
  2. 5 1
      nicegui/functions/open.py

+ 3 - 3
nicegui/client.py

@@ -54,7 +54,7 @@ class Client:
     @property
     def ip(self) -> Optional[str]:
         """Return the IP address of the client, or None if the client is not connected."""
-        return self.environ['asgi.scope']['client'][0] if self.environ else None
+        return self.environ['asgi.scope']['client'][0] if self.has_socket_connection else None
 
     @property
     def has_socket_connection(self) -> bool:
@@ -103,7 +103,7 @@ class Client:
         """Block execution until the client is connected."""
         self.is_waiting_for_connection = True
         deadline = time.time() + timeout
-        while not self.environ:
+        while not self.has_socket_connection:
             if time.time() > deadline:
                 raise TimeoutError(f'No connection after {timeout} seconds')
             await asyncio.sleep(check_interval)
@@ -111,7 +111,7 @@ class Client:
 
     async def disconnected(self, check_interval: float = 0.1) -> None:
         """Block execution until the client disconnects."""
-        if not self.environ:
+        if not self.has_socket_connection:
             await self.connected()
         self.is_waiting_for_disconnect = True
         while self.id in globals.clients:

+ 5 - 1
nicegui/functions/open.py

@@ -1,3 +1,4 @@
+import logging
 from typing import Any, Callable, Union
 
 from .. import globals
@@ -15,4 +16,7 @@ def open(target: Union[Callable[..., Any], str], new_tab: bool = False) -> None:
     :param new_tab: whether to open the target in a new tab
     """
     path = target if isinstance(target, str) else globals.page_routes[target]
-    globals.get_client().open(path, new_tab)
+    if globals.get_client().has_socket_connection:
+        globals.get_client().open(path, new_tab)
+    else:
+        logging.error('Cannot open page because client is not connected, try RedirectResponse from FastAPI instead')