Integrations¶
Application integration¶
Databasez has three common integration styles:
- async context manager lifecycle
- ASGI lifespan wrapper (
database.asgi(...)) - manual startup/shutdown hooks
Async context manager (recommended)¶
Use an app lifespan context and keep lifecycle explicit:
import contextlib
from starlette.applications import Starlette
from databasez import Database
database = Database("sqlite+aiosqlite:///foo.sqlite")
@contextlib.asynccontextmanager
async def lifespan(app): # noqa: ANN001
async with database:
yield
application = Starlette(
lifespan=lifespan,
)
This style works for web and non-web async applications.
ASGI wrapper¶
database.asgi(app, handle_lifespan=False) wraps an ASGI app and injects connect/disconnect on lifespan events.
For frameworks without native lifespan support, use handle_lifespan=True:
from django.core.asgi import get_asgi_application
from databasez import Database
database = Database("sqlite+aiosqlite:///foo.sqlite")
# `handle_lifespan=True` allows integration with frameworks that don't
# expose ASGI lifespan events themselves.
application = database.asgi(get_asgi_application(), handle_lifespan=True)
Manual startup/shutdown hooks¶
Some servers or frameworks use event hooks instead of lifespan context managers.
from ravyn import Ravyn
from databasez import Database
database = Database("sqlite+aiosqlite:///foo.sqlite")
app = Ravyn(routes=[])
@app.on_event("startup")
async def startup() -> None:
await database.connect()
@app.on_event("shutdown")
async def shutdown() -> None:
await database.disconnect()
ORMs¶
There are at least two ORMs using databasez:
When using Edgy, prefer Edgy's own helpers for application integration so you get full registry features.