create_async_session¶
- async safir.database.create_async_session(engine: sqlalchemy.ext.asyncio.engine.AsyncEngine, logger: Optional[structlog.stdlib.BoundLogger] = None, *, statement: Optional[sqlalchemy.sql.selectable.Select] = None) sqlalchemy.ext.asyncio.scoping.async_scoped_session ¶
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.
- Parameters
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 withlimit(1)
before execution. If not provided, database connectivity will not be checked.
- Returns
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