async safir.database.create_async_session(engine, logger=None, *, statement=None)#

Create a new async database session.

Optionally checks that the database is available and retries in a loop for 10s if it is not. This should be used during application startup to wait for any network setup or database proxy sidecar.

  • engine (sqlalchemy.ext.asyncio.AsyncEngine) – Database engine to use for the session.

  • logger (structlog.stdlib.BoundLogger, optional) – Logger for reporting errors. Used only if a statement is provided.

  • statement (sqlalchemy.sql.expression.Select, optional) – If provided, statement to run to check database connectivity. This will be modified with limit(1) before execution. If not provided, database connectivity will not be checked.


session – The database session proxy. This is an asyncio scoped session that is scoped to the current task, which means that it will materialize new AsyncSession objects for each asyncio task (and thus each web request). await session.remove() should be called when the caller is done with the session.

Return type: