1
0
Эх сурвалжийг харах

Merge pull request #238 from zauberzeug/async_shutdown

Rodja Trappe 2 жил өмнө
parent
commit
bac54ba0f7

+ 1 - 1
nicegui/app.py

@@ -38,7 +38,7 @@ class App(FastAPI):
         """
         globals.shutdown_handlers.append(handler)
 
-    async def shutdown(self) -> None:
+    def shutdown(self) -> None:
         """Programmatically shut down NiceGUI.
 
         Only possible when auto-reload is disabled.

+ 4 - 1
nicegui/functions/timer.py

@@ -40,7 +40,8 @@ class Timer:
         with self.slot:
             await self._connected()
             await asyncio.sleep(self.interval)
-            await self._invoke_callback()
+            if globals.state not in [globals.State.STOPPING, globals.State.STOPPED]:
+                await self._invoke_callback()
         self.cleanup()
 
     async def _run_in_loop(self) -> None:
@@ -49,6 +50,8 @@ class Timer:
             while True:
                 if self.slot.parent.client.id not in globals.clients:
                     break
+                if globals.state in [globals.State.STOPPING, globals.State.STOPPED]:
+                    break
                 try:
                     start = time.time()
                     if self.active:

+ 0 - 2
nicegui/nicegui.py

@@ -64,8 +64,6 @@ def handle_shutdown() -> None:
     globals.state = globals.State.STOPPING
     for t in globals.shutdown_handlers:
         safe_invoke(t)
-    for t in background_tasks.running_tasks:
-        t.cancel()
     globals.state = globals.State.STOPPED
 
 

+ 31 - 0
tests/test_lifecycle.py

@@ -47,3 +47,34 @@ def test_connect_disconnect_is_called_for_each_client(screen: Screen):
     screen.open('/')
     screen.wait(0.5)
     assert events == ['connect', 'disconnect', 'connect', 'disconnect', 'connect']
+
+
+def test_startup_and_shutdown_handlers(screen: Screen):
+    events: List[str] = []
+
+    def startup():
+        events.append('startup')
+
+    async def startup_async():
+        events.append('startup_async')
+
+    def shutdown():
+        events.append('shutdown')
+
+    async def shutdown_async():
+        events.append('shutdown_async')
+
+    app.on_startup(startup)
+    app.on_startup(startup_async)
+    app.on_startup(startup_async())
+    app.on_shutdown(shutdown)
+    app.on_shutdown(shutdown_async)
+    app.on_shutdown(shutdown_async())
+
+    screen.open('/')
+    screen.wait(0.5)
+    assert events == ['startup', 'startup_async', 'startup_async']
+
+    app.shutdown()
+    screen.wait(0.5)
+    assert events == ['startup', 'startup_async', 'startup_async', 'shutdown', 'shutdown_async', 'shutdown_async']