justapi — /docs

Lifespan Context Manager

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)

Accessing State

@app.get("/health")
def health(request):
    db = request.app.state.db
    return {"status": "ok" if db else "error"}

Multiple Resources

@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)

See Also

JustAPI v2.0.9 — Open Source MIT License · Built with WebTUI · GitHub

NORMAL master justapi/docs
utf-8 Top 1:1