Setup¶
fastsqla.lifespan
¶
Use fastsqla.lifespan
to set up SQLAlchemy.
In an ASGI application, lifespan events are used to communicate startup & shutdown events.
The lifespan
parameter of
the FastAPI
app can be assigned to a context manager, which is opened when the app
starts and closed when the app stops.
In order for FastSQLA
to setup SQLAlchemy
before the app is started, set
lifespan
parameter to fastsqla.lifespan
:
If multiple lifespan contexts are required, create an async context manager function to handle them and set it as the app's lifespan:
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastsqla import lifespan as fastsqla_lifespan
from this_other_library import another_lifespan
@asynccontextmanager
async def lifespan(app:FastAPI) -> AsyncGenerator[dict, None]:
async with AsyncExitStack() as stack:
yield {
**stack.enter_async_context(lifespan(app)),
**stack.enter_async_context(another_lifespan(app)),
}
app = FastAPI(lifespan=lifespan)
To learn more about lifespan protocol:
Configuration¶
Configuration is done exclusively via environment variables, adhering to the Twelve-Factor App methodology.
The only required key is SQLALCHEMY_URL
, which defines the database URL. It
specifies the database driver in the URL's scheme and allows embedding driver parameters
in the query string. Example:
sqlite+aiosqlite:////tmp/test.db?check_same_thread=false
All parameters of sqlalchemy.create_engine
can be configured by setting environment
variables, with each parameter name prefixed by SQLALCHEMY_
.
Note
FastSQLA is case-insensitive when reading environment variables, so parameter
names prefixed with SQLALCHEMY_
can be provided in any letter case.