From ab67f907997b4b5567cb54a02ea92133ffbec383 Mon Sep 17 00:00:00 2001 From: Falko Schindler Date: Wed, 25 Oct 2023 09:46:27 +0200 Subject: [PATCH 1/3] add startup and shutdown handlers to existing FastAPI app --- nicegui/ui_run_with.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/nicegui/ui_run_with.py b/nicegui/ui_run_with.py index d6d94a02a..d23a0e1f7 100644 --- a/nicegui/ui_run_with.py +++ b/nicegui/ui_run_with.py @@ -5,6 +5,7 @@ from . import core, storage from .language import Language +from .nicegui import _shutdown, _startup def run_with( @@ -52,3 +53,5 @@ def run_with( storage.set_storage_secret(storage_secret) app.mount(mount_path, core.app) + app.on_event('startup')(_startup) + app.on_event('shutdown')(_shutdown) From 18c7eae71b6cddb7e8b7541ecbc0b5e92be06e06 Mon Sep 17 00:00:00 2001 From: Falko Schindler Date: Thu, 26 Oct 2023 09:04:18 +0200 Subject: [PATCH 2/3] improve lifespan registration in ui_run_with.py --- nicegui/ui_run_with.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/nicegui/ui_run_with.py b/nicegui/ui_run_with.py index d23a0e1f7..8feb4ca04 100644 --- a/nicegui/ui_run_with.py +++ b/nicegui/ui_run_with.py @@ -1,3 +1,4 @@ +from contextlib import asynccontextmanager from pathlib import Path from typing import Optional, Union @@ -53,5 +54,13 @@ def run_with( storage.set_storage_secret(storage_secret) app.mount(mount_path, core.app) - app.on_event('startup')(_startup) - app.on_event('shutdown')(_shutdown) + main_app_lifespan = app.router.lifespan_context + + @asynccontextmanager + async def lifespan_wrapper(app): + _startup() + async with main_app_lifespan(app) as maybe_state: + yield maybe_state + _shutdown() + + app.router.lifespan_context = lifespan_wrapper From 21d3bb36d26d424ec5906d3e2441861c4829aa5a Mon Sep 17 00:00:00 2001 From: Falko Schindler Date: Thu, 26 Oct 2023 13:14:56 +0200 Subject: [PATCH 3/3] cleanup --- nicegui/ui_run_with.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nicegui/ui_run_with.py b/nicegui/ui_run_with.py index 8feb4ca04..8f23aee42 100644 --- a/nicegui/ui_run_with.py +++ b/nicegui/ui_run_with.py @@ -59,8 +59,8 @@ def run_with( @asynccontextmanager async def lifespan_wrapper(app): _startup() - async with main_app_lifespan(app) as maybe_state: - yield maybe_state + async with main_app_lifespan(app): + yield _shutdown() app.router.lifespan_context = lifespan_wrapper