Browse Source

renamed client.handshake to client.connected

Rodja Trappe 2 years ago
parent
commit
048684ce42

+ 1 - 1
examples/infinite_scroll/main.py

@@ -9,7 +9,7 @@ async def page(client: Client):
     async def check():
     async def check():
         if await ui.run_javascript('window.pageYOffset >= document.body.offsetHeight - 2 * window.innerHeight'):
         if await ui.run_javascript('window.pageYOffset >= document.body.offsetHeight - 2 * window.innerHeight'):
             ui.image(f'https://picsum.photos/640/360?{time.time()}')
             ui.image(f'https://picsum.photos/640/360?{time.time()}')
-    await client.handshake()
+    await client.connected()
     ui.timer(0.1, check)
     ui.timer(0.1, check)
 
 
 
 

+ 1 - 1
examples/map/main.py

@@ -15,7 +15,7 @@ locations = {
 async def main_page(client: Client):
 async def main_page(client: Client):
     map = leaflet().classes('w-full h-96')
     map = leaflet().classes('w-full h-96')
     selection = ui.select(locations, on_change=lambda e: map.set_location(e.value)).classes('w-40')
     selection = ui.select(locations, on_change=lambda e: map.set_location(e.value)).classes('w-40')
-    await client.handshake()  # wait for websocket connection
+    await client.connected()  # wait for websocket connection
     selection.set_value(next(iter(locations)))  # trigger map.set_location with first location in selection
     selection.set_value(next(iter(locations)))  # trigger map.set_location with first location in selection
 
 
 
 

+ 5 - 5
nicegui/client.py

@@ -30,7 +30,7 @@ class Client:
 
 
         self.elements: Dict[int, Element] = {}
         self.elements: Dict[int, Element] = {}
         self.next_element_id: int = 0
         self.next_element_id: int = 0
-        self.is_waiting_for_handshake: bool = False
+        self.is_waiting_for_connection: bool = False
         self.environ: Optional[Dict[str, Any]] = None
         self.environ: Optional[Dict[str, Any]] = None
         self.shared = shared
         self.shared = shared
 
 
@@ -84,14 +84,14 @@ class Client:
             'socket_io_js_extra_headers': globals.socket_io_js_extra_headers,
             'socket_io_js_extra_headers': globals.socket_io_js_extra_headers,
         }, status_code, {'Cache-Control': 'no-store', 'X-NiceGUI-Content': 'page'})
         }, status_code, {'Cache-Control': 'no-store', 'X-NiceGUI-Content': 'page'})
 
 
-    async def handshake(self, timeout: float = 3.0, check_interval: float = 0.1) -> None:
-        self.is_waiting_for_handshake = True
+    async def connected(self, timeout: float = 3.0, check_interval: float = 0.1) -> None:
+        self.is_waiting_for_connection = True
         deadline = time.time() + timeout
         deadline = time.time() + timeout
         while not self.environ:
         while not self.environ:
             if time.time() > deadline:
             if time.time() > deadline:
-                raise TimeoutError(f'No handshake after {timeout} seconds')
+                raise TimeoutError(f'No connection after {timeout} seconds')
             await asyncio.sleep(check_interval)
             await asyncio.sleep(check_interval)
-        self.is_waiting_for_handshake = False
+        self.is_waiting_for_connection = False
 
 
     async def run_javascript(self, code: str, *,
     async def run_javascript(self, code: str, *,
                              respond: bool = True, timeout: float = 1.0, check_interval: float = 0.01) -> Optional[str]:
                              respond: bool = True, timeout: float = 1.0, check_interval: float = 0.01) -> Optional[str]:

+ 2 - 1
nicegui/functions/javascript.py

@@ -7,6 +7,7 @@ async def run_javascript(code: str, *,
                          respond: bool = True, timeout: float = 1.0, check_interval: float = 0.01) -> Optional[str]:
                          respond: bool = True, timeout: float = 1.0, check_interval: float = 0.01) -> Optional[str]:
     client = globals.get_client()
     client = globals.get_client()
     if not client.has_socket_connection:
     if not client.has_socket_connection:
-        raise RuntimeError('Cannot run JavaScript before client handshake.')
+        raise RuntimeError(
+            'Cannot run JavaScript before client is connected; try "await client.connected()" or "client.on_connect(...)".')
 
 
     return await client.run_javascript(code, respond=respond, timeout=timeout, check_interval=check_interval)
     return await client.run_javascript(code, respond=respond, timeout=timeout, check_interval=check_interval)

+ 5 - 5
nicegui/functions/timer.py

@@ -40,14 +40,14 @@ class Timer:
 
 
     async def _run_once(self) -> None:
     async def _run_once(self) -> None:
         with self.slot:
         with self.slot:
-            await self._handshake()
+            await self._connected()
             await asyncio.sleep(self.interval)
             await asyncio.sleep(self.interval)
             await self._invoke_callback()
             await self._invoke_callback()
         self.cleanup()
         self.cleanup()
 
 
     async def _run_in_loop(self) -> None:
     async def _run_in_loop(self) -> None:
         with self.slot:
         with self.slot:
-            await self._handshake()
+            await self._connected()
             while True:
             while True:
                 if self.slot.parent.client.id not in globals.clients:
                 if self.slot.parent.client.id not in globals.clients:
                     break
                     break
@@ -72,12 +72,12 @@ class Timer:
         except Exception:
         except Exception:
             traceback.print_exc()
             traceback.print_exc()
 
 
-    async def _handshake(self) -> None:
-        '''Wait for the client handshake before the timer callback can can be allowed to manipulate the state.
+    async def _connected(self) -> None:
+        '''Wait for the client connection before the timer callback can can be allowed to manipulate the state.
         See https://github.com/zauberzeug/nicegui/issues/206 for details.
         See https://github.com/zauberzeug/nicegui/issues/206 for details.
         '''
         '''
         if not self.slot.parent.client.shared:
         if not self.slot.parent.client.shared:
-            await self.slot.parent.client.handshake()
+            await self.slot.parent.client.connected()
 
 
     def cleanup(self) -> None:
     def cleanup(self) -> None:
         self.slot = None
         self.slot = None

+ 1 - 1
nicegui/page.py

@@ -64,7 +64,7 @@ class page:
                         await AsyncUpdater(result)
                         await AsyncUpdater(result)
                 task = create_task(wait_for_result())
                 task = create_task(wait_for_result())
                 deadline = time.time() + self.response_timeout
                 deadline = time.time() + self.response_timeout
-                while task and not client.is_waiting_for_handshake and not task.done():
+                while task and not client.is_waiting_for_connection and not task.done():
                     if time.time() > deadline:
                     if time.time() > deadline:
                         raise TimeoutError(f'Response not ready after {self.response_timeout} seconds')
                         raise TimeoutError(f'Response not ready after {self.response_timeout} seconds')
                     await asyncio.sleep(0.1)
                     await asyncio.sleep(0.1)

+ 6 - 6
tests/test_auto_context.py

@@ -49,12 +49,12 @@ def test_adding_elements_with_async_await(screen: Screen):
     cB.find_element(By.XPATH, f'.//*[contains(text(), "B")]')
     cB.find_element(By.XPATH, f'.//*[contains(text(), "B")]')
 
 
 
 
-def test_autoupdate_after_handshake(screen: Screen):
+def test_autoupdate_after_connected(screen: Screen):
     @ui.page('/')
     @ui.page('/')
     async def page(client: Client):
     async def page(client: Client):
-        ui.label('before handshake')
-        await client.handshake()
-        ui.label('after handshake')
+        ui.label('before connected')
+        await client.connected()
+        ui.label('after connected')
         await asyncio.sleep(1)
         await asyncio.sleep(1)
         ui.label('one')
         ui.label('one')
         await asyncio.sleep(1)
         await asyncio.sleep(1)
@@ -63,8 +63,8 @@ def test_autoupdate_after_handshake(screen: Screen):
         ui.label('three')
         ui.label('three')
 
 
     screen.open('/')
     screen.open('/')
-    screen.should_contain('before handshake')
-    screen.should_contain('after handshake')
+    screen.should_contain('before connected')
+    screen.should_contain('after connected')
     screen.should_not_contain('one')
     screen.should_not_contain('one')
     screen.wait_for('one')
     screen.wait_for('one')
     screen.should_not_contain('two')
     screen.should_not_contain('two')

+ 2 - 2
tests/test_javascript.py

@@ -24,7 +24,7 @@ def test_run_javascript_on_value_change(screen: Screen):
         async def set_title(e: ValueChangeEventArguments) -> None:
         async def set_title(e: ValueChangeEventArguments) -> None:
             await ui.run_javascript(f'document.title = "{e.value}"')
             await ui.run_javascript(f'document.title = "{e.value}"')
         ui.radio(['Page Title A', 'Page Title B'], on_change=set_title)
         ui.radio(['Page Title A', 'Page Title B'], on_change=set_title)
-        await client.handshake()
+        await client.connected()
         await ui.run_javascript('document.title = "Initial Page Title"')
         await ui.run_javascript('document.title = "Initial Page Title"')
 
 
     screen.open('/')
     screen.open('/')
@@ -38,7 +38,7 @@ def test_run_javascript_on_value_change(screen: Screen):
     assert screen.selenium.title == 'Page Title A'
     assert screen.selenium.title == 'Page Title A'
 
 
 
 
-def test_run_javascript_before_client_handshake(screen: Screen):
+def test_run_javascript_before_client_connected(screen: Screen):
     @ui.page('/')
     @ui.page('/')
     async def page():
     async def page():
         ui.label('before js')
         ui.label('before js')

+ 6 - 6
tests/test_page.py

@@ -100,7 +100,7 @@ def test_shared_and_private_pages(screen: Screen):
     assert uuid1 == uuid2
     assert uuid1 == uuid2
 
 
 
 
-def test_wait_for_handshake(screen: Screen):
+def test_wait_for_connected(screen: Screen):
     async def load() -> None:
     async def load() -> None:
         label.text = 'loading...'
         label.text = 'loading...'
         # NOTE we can not use asyncio.create_task() here because we are on a different thread than the NiceGUI event loop
         # NOTE we can not use asyncio.create_task() here because we are on a different thread than the NiceGUI event loop
@@ -114,18 +114,18 @@ def test_wait_for_handshake(screen: Screen):
     async def page(client: Client):
     async def page(client: Client):
         global label
         global label
         label = ui.label()
         label = ui.label()
-        await client.handshake()
+        await client.connected()
         await load()
         await load()
 
 
     screen.open('/')
     screen.open('/')
     screen.should_contain('delayed data has been loaded')
     screen.should_contain('delayed data has been loaded')
 
 
 
 
-def test_adding_elements_after_handshake(screen: Screen):
+def test_adding_elements_after_connected(screen: Screen):
     @ui.page('/')
     @ui.page('/')
     async def page(client: Client):
     async def page(client: Client):
         ui.label('before')
         ui.label('before')
-        await client.handshake()
+        await client.connected()
         ui.label('after')
         ui.label('after')
 
 
     screen.open('/')
     screen.open('/')
@@ -144,10 +144,10 @@ def test_exception(screen: Screen):
     screen.assert_py_logger('ERROR', 'some exception')
     screen.assert_py_logger('ERROR', 'some exception')
 
 
 
 
-def test_exception_after_handshake(screen: Screen):
+def test_exception_after_connected(screen: Screen):
     @ui.page('/')
     @ui.page('/')
     async def page(client: Client):
     async def page(client: Client):
-        await client.handshake()
+        await client.connected()
         ui.label('this is shown')
         ui.label('this is shown')
         raise Exception('some exception')
         raise Exception('some exception')
 
 

+ 7 - 7
website/reference.py

@@ -659,29 +659,29 @@ If the page function expects a `request` argument, the request object is automat
 
 
         ui.link('Say hi to Santa!', 'repeat/Ho! /3')
         ui.link('Say hi to Santa!', 'repeat/Ho! /3')
 
 
-    @example('''#### Wait for Handshake with Client
+    @example('''#### Wait for Client Connection
 
 
 To wait for a client connection, you can add a `client` argument to the decorated page function
 To wait for a client connection, you can add a `client` argument to the decorated page function
-and await `client.handshake()`.
+and await `client.connected()`.
 All code below that statement is executed after the websocket connection between server and client has been established.
 All code below that statement is executed after the websocket connection between server and client has been established.
 
 
 For example, this allows you to run JavaScript commands; which is only possible with a client connection (see [#112](https://github.com/zauberzeug/nicegui/issues/112)).
 For example, this allows you to run JavaScript commands; which is only possible with a client connection (see [#112](https://github.com/zauberzeug/nicegui/issues/112)).
 Also it is possible to do async stuff while the user already sees some content.
 Also it is possible to do async stuff while the user already sees some content.
 ''')
 ''')
-    def wait_for_handshake_example():
+    def wait_for_connected_example():
         import asyncio
         import asyncio
 
 
         from nicegui import Client
         from nicegui import Client
 
 
-        @ui.page('/wait_for_handshake')
-        async def wait_for_handshake(client: Client):
+        @ui.page('/wait_for_connection')
+        async def wait_for_connection(client: Client):
             ui.label('This text is displayed immediately.')
             ui.label('This text is displayed immediately.')
-            await client.handshake()
+            await client.connected()
             await asyncio.sleep(2)
             await asyncio.sleep(2)
             ui.label('This text is displayed 2 seconds after the page has been fully loaded.')
             ui.label('This text is displayed 2 seconds after the page has been fully loaded.')
             ui.label(f'The IP address {client.ip} was obtained from the websocket.')
             ui.label(f'The IP address {client.ip} was obtained from the websocket.')
 
 
-        ui.link('wait for handshake', wait_for_handshake)
+        ui.link('wait for connection', wait_for_connection)
 
 
     @example('''#### Page Layout
     @example('''#### Page Layout