Просмотр исходного кода

fix page examples; fix on_connect for non-shared pages

Falko Schindler 2 лет назад
Родитель
Сommit
a2ba6269c6
3 измененных файлов с 27 добавлено и 11 удалено
  1. 11 6
      main.py
  2. 14 2
      nicegui/elements/page.py
  3. 2 3
      nicegui/nicegui.py

+ 11 - 6
main.py

@@ -584,11 +584,13 @@ with example(async_handlers):
 h3('Pages and Routes')
 h3('Pages and Routes')
 
 
 with example(ui.page):
 with example(ui.page):
-    with ui.page('/other_page'):
+    @ui.page('/other_page')
+    def other_page():
         ui.label('Welcome to the other side')
         ui.label('Welcome to the other side')
         ui.link('Back to main page', '#page')
         ui.link('Back to main page', '#page')
 
 
-    with ui.page('/dark_page', dark=True):
+    @ui.page('/dark_page', dark=True)
+    def dark_page():
         ui.label('Welcome to the dark side')
         ui.label('Welcome to the dark side')
         ui.link('Back to main page', '#page')
         ui.link('Back to main page', '#page')
 
 
@@ -596,11 +598,12 @@ with example(ui.page):
     ui.link('Visit dark page', 'dark_page')
     ui.link('Visit dark page', 'dark_page')
 
 
 with example(ui.open):
 with example(ui.open):
-    with ui.page('/yet_another_page') as other:
+    @ui.page('/yet_another_page')
+    def yet_another_page():
         ui.label('Welcome to yet another page')
         ui.label('Welcome to yet another page')
         ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
         ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
 
 
-    ui.button('REDIRECT', on_click=lambda e: ui.open(other, e.socket))
+    ui.button('REDIRECT', on_click=lambda e: ui.open('yet_another_page', e.socket))
 
 
 add_route = '''#### Route
 add_route = '''#### Route
 
 
@@ -655,9 +658,11 @@ with example(sessions):
         id_counter[request.session_id] += 1
         id_counter[request.session_id] += 1
         visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
         visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
 
 
-    with ui.page('/session_demo', on_connect=handle_connection) as page:
+    @ui.page('/session_demo', on_connect=handle_connection)
+    def session_demo():
+        global visits
         visits = ui.label()
         visits = ui.label()
 
 
-    ui.link('Visit session demo', page)
+    ui.link('Visit session demo', 'session_demo')
 
 
 ui.run()
 ui.run()

+ 14 - 2
nicegui/elements/page.py

@@ -1,10 +1,12 @@
+from __future__ import annotations
+
 import asyncio
 import asyncio
 import inspect
 import inspect
 import time
 import time
 import uuid
 import uuid
 from dataclasses import dataclass
 from dataclasses import dataclass
 from functools import wraps
 from functools import wraps
-from typing import Callable, Optional
+from typing import Awaitable, Callable, Optional
 
 
 import justpy as jp
 import justpy as jp
 from addict import Dict
 from addict import Dict
@@ -17,9 +19,19 @@ from ..helpers import is_coroutine
 
 
 @dataclass
 @dataclass
 class PageBuilder:
 class PageBuilder:
-    function: Callable
+    function: Callable[[], Awaitable[Page]]
     shared: bool
     shared: bool
 
 
+    _shared_page: Optional[Page] = None
+
+    async def build(self) -> None:
+        assert self.shared
+        self._shared_page = await self.function()
+
+    async def route_function(self, request: Request) -> Page:
+        page = self._shared_page if self.shared else await self.function()
+        return await page._route_function(request)
+
 
 
 class Page(jp.QuasarPage):
 class Page(jp.QuasarPage):
 
 

+ 2 - 3
nicegui/nicegui.py

@@ -30,9 +30,8 @@ async def startup():
     jp.Route("/{path:path}", error404, last=True)
     jp.Route("/{path:path}", error404, last=True)
     for route, page_builder in globals.page_builders.items():
     for route, page_builder in globals.page_builders.items():
         if page_builder.shared:
         if page_builder.shared:
-            jp.Route(route, (await page_builder.function())._route_function)
-        else:
-            jp.Route(route, page_builder.function)
+            page_builder.build()
+        jp.Route(route, page_builder.route_function)
     globals.tasks.extend(create_task(t.coro, name=t.name) for t in Timer.prepared_coroutines)
     globals.tasks.extend(create_task(t.coro, name=t.name) for t in Timer.prepared_coroutines)
     Timer.prepared_coroutines.clear()
     Timer.prepared_coroutines.clear()
     globals.tasks.extend(create_task(t, name='startup task')
     globals.tasks.extend(create_task(t, name='startup task')