Skip to content

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:

from fastapi import FastAPI
from fastsqla import lifespan


app = FastAPI(lifespan=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.

Examples

  1. PostgreSQL url using asyncpg driver with a pool_recycle of 30 minutes:

    export SQLALCHEMY_URL=postgresql+asyncpg://postgres@localhost/postgres
    export SQLALCHEMY_POOL_RECYCLE=1800
    
  2. SQLite db file using aiosqlite driver with a pool_size of 50:

    export sqlalchemy_url=sqlite+aiosqlite:///tmp/test.db?check_same_thread=false
    export sqlalchemy_pool_size=10
    
  3. MariaDB url using aiomysql driver with echo parameter set to True

    export sqlalchemy_url=mysql+aiomysql://bob:password!@db.example.com/app
    export sqlalchemy_echo=true