tenseleyflow/sway / 2c94d2b

Browse files

Use FastAPI lifespan instead of deprecated on_event

Authored by mfwolffe <wolffemf@dukes.jmu.edu>
SHA
2c94d2b42d3642cdc157ddba5bfa4c07909b576a
Parents
5ab3e61
Tree
b3611fe

1 changed file

StatusFile+-
M src/dlm_sway/serve/app.py 15 6
src/dlm_sway/serve/app.pymodified
@@ -89,6 +89,8 @@ def create_app(
8989
     a TestClient.
9090
     """
9191
     try:
92
+        from contextlib import asynccontextmanager
93
+
9294
         from fastapi import FastAPI, HTTPException, Request, status
9395
         from fastapi.responses import JSONResponse
9496
     except ImportError as exc:
@@ -102,6 +104,18 @@ def create_app(
102104
     request_count = 0
103105
     total_run_seconds = 0.0
104106
 
107
+    # Capture cache in the lifespan closure so the shutdown leg runs
108
+    # ``evict_all`` (the on_event API is deprecated in FastAPI 0.110+).
109
+    _cache_for_lifespan = cache
110
+
111
+    @asynccontextmanager
112
+    async def _lifespan(app: Any) -> Any:
113
+        del app
114
+        try:
115
+            yield
116
+        finally:
117
+            _cache_for_lifespan.evict_all()
118
+
105119
     app = FastAPI(
106120
         title="sway",
107121
         version=__version__,
@@ -109,6 +123,7 @@ def create_app(
109123
             "Warm-backend HTTP API for sway. POST /run accepts a spec; "
110124
             "the daemon keeps backends loaded between calls."
111125
         ),
126
+        lifespan=_lifespan,
112127
     )
113128
 
114129
     # -- auth middleware --------------------------------------------------
@@ -265,12 +280,6 @@ def create_app(
265280
             "request_seconds": elapsed,
266281
         }
267282
 
268
-    # -- shutdown --------------------------------------------------------
269
-
270
-    @app.on_event("shutdown")
271
-    async def _on_shutdown() -> None:
272
-        cache.evict_all()
273
-
274283
     # Stash the cache + counters on the app so tests can introspect.
275284
     app.state.sway_cache = cache
276285