Skip to content

Lifespan Events

Use @asynccontextmanager for startup/shutdown:

from contextlib import asynccontextmanager
from justapi import JustAPIApp
@asynccontextmanager
async 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)
@app.get("/health")
def health(request):
db = request.app.state.db
return {"status": "ok" if db else "error"}
@asynccontextmanager
async 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)