We currently support generator based dependencies, but not context managers. For instance the following works:
async def provide_connection(
self,
state: State,
scope: Scope,
) -> AsyncGenerator[Union[PoolConnectionProxy,Connection], None]: # noqa: UP007
"""Create a connection instance.
Args:
state: The ``Litestar.state`` instance.
scope: The current connection's scope.
Returns:
A connection instance.
"""
connection = cast("Optional[Union[PoolConnectionProxy,Connection]]", get_scope_state(scope, CONNECTION_SCOPE_KEY))
if connection is None:
pool = cast("Pool", state.get(self.pool_app_state_key))
async with pool.acquire() as connection:
set_scope_state(scope, CONNECTION_SCOPE_KEY, connection)
yield connection
But adding an context manager decorator like this:
@asynccontextmanager
async def provide_connection(
self,
state: State,
scope: Scope,
) -> AsyncGenerator[Union[PoolConnectionProxy,Connection], None]: # noqa: UP007
"""Create a connection instance.
Args:
state: The ``Litestar.state`` instance.
scope: The current connection's scope.
Returns:
A connection instance.
"""
connection = cast("Optional[Union[PoolConnectionProxy,Connection]]", get_scope_state(scope, CONNECTION_SCOPE_KEY))
if connection is None:
pool = cast("Pool", state.get(self.pool_app_state_key))
async with pool.acquire() as connection:
set_scope_state(scope, CONNECTION_SCOPE_KEY, connection)
yield connection
produces
msgspec.ValidationError: Unsupported type: <class 'contextlib._AsyncGeneratorContextManager'> - at `$.db_connection`
No response
No response
No response
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too