Lifespan Events
Lifespan Context Manager
Section titled “Lifespan Context Manager”Use @asynccontextmanager for startup/shutdown:
from contextlib import asynccontextmanagerfrom justapi import JustAPIApp
@asynccontextmanagerasync def lifespan(app): # Startup: run before the server starts print("Starting up...") db = await create_connection() app.state.db = db yield # Shutdown: run after the server stops print("Shutting down...") await db.close()
app = JustAPIApp(lifespan=lifespan)Accessing State
Section titled “Accessing State”@app.get("/health")def health(request): db = request.app.state.db return {"status": "ok" if db else "error"}Multiple Resources
Section titled “Multiple Resources”@asynccontextmanagerasync def lifespan(app): # Start all resources app.state.db = await create_db() app.state.cache = await create_cache() app.state.queue = await create_queue() yield # Stop all resources await app.state.queue.close() await app.state.cache.close() await app.state.db.close()
app = JustAPIApp(lifespan=lifespan)See Also
Section titled “See Also”- Settings & Environment Variables — configuration
- Health Checks — monitoring
- SQL Databases — database lifecycle