Prechádzať zdrojové kódy

introduce on_startup to schedule synchronous or asynchronous startup tasks

Falko Schindler 4 rokov pred
rodič
commit
0811656782
3 zmenil súbory, kde vykonal 14 pridanie a 1 odobranie
  1. 3 0
      nicegui/nicegui.py
  2. 2 1
      nicegui/timer.py
  3. 9 0
      nicegui/ui.py

+ 3 - 0
nicegui/nicegui.py

@@ -1,4 +1,5 @@
 #!/usr/bin/env python3
 #!/usr/bin/env python3
+from typing import Awaitable, Callable
 import justpy as jp
 import justpy as jp
 import uvicorn
 import uvicorn
 import sys
 import sys
@@ -46,6 +47,8 @@ async def binding_loop():
 @jp.app.on_event('startup')
 @jp.app.on_event('startup')
 def startup():
 def startup():
     [jp.run_task(t) for t in Timer.tasks]
     [jp.run_task(t) for t in Timer.tasks]
+    [t() for t in Ui.startup_tasks if isinstance(t, Callable)]
+    [jp.run_task(t) for t in Ui.startup_tasks if isinstance(t, Awaitable)]
     jp.run_task(binding_loop())
     jp.run_task(binding_loop())
 
 
 Element.wp = wp
 Element.wp = wp

+ 2 - 1
nicegui/timer.py

@@ -1,6 +1,7 @@
 import asyncio
 import asyncio
 import time
 import time
 import traceback
 import traceback
+from typing import Awaitable
 from binding import BindableProperty
 from binding import BindableProperty
 from .elements.element import Element
 from .elements.element import Element
 from .utils import handle_exceptions
 from .utils import handle_exceptions
@@ -11,7 +12,7 @@ class Timer:
 
 
     active = BindableProperty
     active = BindableProperty
 
 
-    def __init__(self, interval, callback, *, active=True, once=False):
+    def __init__(self, interval: float, callback: Awaitable, *, active: bool = True, once: bool = False):
         """Timer
         """Timer
 
 
         One major drive behind the creation of NiceGUI was the necessity to have a simple approach to update the interface in regular intervals, for example to show a graph with incomming measurements.
         One major drive behind the creation of NiceGUI was the necessity to have a simple approach to update the interface in regular intervals, for example to show a graph with incomming measurements.

+ 9 - 0
nicegui/ui.py

@@ -1,3 +1,6 @@
+from typing import Awaitable, Callable, List, Union
+
+
 class Ui:
 class Ui:
 
 
     from .elements.button import Button as button
     from .elements.button import Button as button
@@ -25,3 +28,9 @@ class Ui:
     from .elements.card import Card as card
     from .elements.card import Card as card
 
 
     from .timer import Timer as timer
     from .timer import Timer as timer
+
+    startup_tasks: List[Union[Callable, Awaitable]] = []
+
+    def on_startup(self, task: Union[Callable, Awaitable]):
+
+        self.startup_tasks.append(task)