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 callinginitialize
.Methods Summary
__call__
()Create a database session and open a transaction.
aclose
()Shut down the database engine.
initialize
(url, password, *[, ...])Initialize the session dependency.
Methods Documentation
- async __call__() AsyncIterator[sqlalchemy.ext.asyncio.scoping.async_scoped_session] ¶
Create a database session and open a transaction.
By default, this implements a policy of one request equals one transaction, which is closed when that request returns. To disable managed transactions, pass
manage_transactions=False
to theinitialize
method.- Returns
session – The newly-created session.
- Return type
- async initialize(url: str, password: Optional[str], *, isolation_level: Optional[str] = None, manage_transactions: bool = True) None ¶
Initialize the session dependency.
- Parameters
url (
str
) – Database connection URL, not including the password.isolation_level (
str
, optional) – If specified, sets a non-default isolation level for the database engine.manage_transactions (
bool
, optional) – Whether the dependency should open a new transaction for each request and commit that transaction at the end of the request. This is the default behavior; to manage transactions manually, set this parameter toFalse
. (Disabling managed transactions may be necessary if the application database code has to retry failed transactions due to a non-default isolation level.)