Debian Codegraph @

docs/examples/contrib/sqlalchemy/plugins/sqlalchemy_async_dependencies.py

raw
1 from __future__ import annotations
2
3 from typing import TYPE_CHECKING
4
5 from sqlalchemy import select
6
7 from litestar import Litestar, post
8 from litestar.di import NamedDependency
9 from litestar.plugins.sqlalchemy import SQLAlchemyAsyncConfig, SQLAlchemyInitPlugin
10
11 if TYPE_CHECKING:
12 from typing import Tuple
13
14 from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession
15
16
17 @post("/")
18 async def handler(
19 db_session: NamedDependency[AsyncSession], db_engine: NamedDependency[AsyncEngine]
20 ) -> Tuple[int, int]:
21 one = (await db_session.execute(select(1))).scalar()
22
23 async with db_engine.begin() as conn:
24 two = (await conn.execute(select(2))).scalar()
25
26 return one, two
27
28
29 config = SQLAlchemyAsyncConfig(connection_string="sqlite+aiosqlite:///async.sqlite")
30 plugin = SQLAlchemyInitPlugin(config=config)
31 app = Litestar(route_handlers=[handler], plugins=[plugin])