DatabaseSessionDependency#

class safir.dependencies.db_session.DatabaseSessionDependency#

Bases: object

Manages an async per-request SQLAlchemy session.

Notes

Creation of the database session factory has to be deferred until the configuration has been loaded, which in turn is deferred until app startup.

In the app startup hook, run:

await db_session_dependency.initialize(database_url)

In the app shutdown hook, run:

await db_session_dependency.aclose()

An isolation level may optionally be configured when calling initialize. By default, a transaction is opened for every request and committed at the end of that request. This can be configured when calling initialize.

Methods Summary

__call__()

Return the database session manager.

aclose()

Shut down the database engine.

initialize(url, password, *[, connect_args, ...])

Initialize the session dependency.

Methods Documentation

async __call__()#

Return the database session manager.

Returns:

The newly-created session.

Return type:

sqlalchemy.ext.asyncio.AsyncSession

async aclose()#

Shut down the database engine.

Return type:

None

async initialize(url, password, *, connect_args=None, isolation_level=None, max_overflow=None, pool_pre_ping=None, pool_recycle=None, pool_size=None, pool_timeout=None)#

Initialize the session dependency.

Parameters:
  • url (Union[str, Url]) – Database connection URL, not including the password.

  • password (Union[str, SecretStr, None]) – Database connection password.

  • connect_args (Optional[dict[str, Any]], default: None) – Additional connection arguments to pass directly to the underlying database driver.

  • isolation_level (Optional[str], default: None) – If specified, sets a non-default isolation level for the database engine.

  • max_overflow (Optional[int], default: None) – Maximum number of connections over the pool size for surge traffic.

  • pool_pre_ping (Optional[bool], default: None) – Check that a connection is alive before returning it to a session.

  • pool_recycle (Optional[int], default: None) – If set to an integer, discard any idle connection open for longer than the provided number of seconds rather than attempting to reuse it. If the connection idle timeout on the database server is known, setting this to slightly less than that timeout will produce the best results.

  • pool_size (Optional[int], default: None) – Connection pool size.

  • pool_timeout (Optional[float], default: None) – How long to wait for a connection from the connection pool before giving up.

Return type:

None

This page was last modified on .