Starlette#
SQLSpec provides a Starlette extension that hooks database sessions into the ASGI lifecycle. The extension uses Starlette's lifespan context to manage connection pools and provides middleware for request-scoped sessions.
Installation#
Install SQLSpec with the Starlette extra:
uv add "sqlspec[starlette]"
pip install "sqlspec[starlette]"
poetry add "sqlspec[starlette]"
pdm add "sqlspec[starlette]"
Basic Setup#
Create a SQLSpec instance, register your database config, and attach the plugin to your Starlette app. The plugin adds middleware that makes sessions available during each request.
starlette basic setup#from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import Route
from sqlspec import SQLSpec
from sqlspec.adapters.aiosqlite import AiosqliteConfig, AiosqliteDriver
from sqlspec.extensions.starlette import SQLSpecPlugin
sqlspec = SQLSpec()
sqlspec.add_config(AiosqliteConfig(connection_config={"database": ":memory:"}))
# Create plugin at module level
db_plugin = SQLSpecPlugin(sqlspec)
async def health(request: Request) -> JSONResponse:
db: AiosqliteDriver = db_plugin.get_session(request)
result = await db.execute("select 1 as ok")
return JSONResponse(result.one())
app = Starlette(routes=[Route("/health", health)])
db_plugin.init_app(app) # Initialize plugin with app
Key Concepts#
- Lifespan Management
The plugin registers startup and shutdown handlers to initialize and close connection pools. Pools are created when the application starts and released when it stops.
- Async Sessions
Starlette is async-first. Use async adapters like
AiosqliteConfig,AsyncpgConfig, orPsycopgAsyncConfigfor optimal performance.- Request State
Sessions are stored in
request.stateand can be accessed in route handlers or middleware that runs after the SQLSpec middleware.