Debian Codegraph @

docs/examples/plugins/sqlalchemy_init_plugin/sqlalchemy_async.py

raw
1 from __future__ import annotations
2
3 from typing import TYPE_CHECKING
4
5 from sqlalchemy import text
6
7 from litestar import Litestar, get
8 from litestar.di import NamedDependency
9 from litestar.plugins.sqlalchemy import SQLAlchemyAsyncConfig, SQLAlchemyInitPlugin
10
11 if TYPE_CHECKING:
12 from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession
13
14
15 @get(path="/sqlalchemy-app")
16 async def async_sqlalchemy_init(
17 db_session: NamedDependency[AsyncSession], db_engine: NamedDependency[AsyncEngine]
18 ) -> str:
19 """Interact with SQLAlchemy engine and session."""
20 one = (await db_session.execute(text("SELECT 1"))).scalar_one()
21
22 async with db_engine.begin() as conn:
23 two = (await conn.execute(text("SELECT 2"))).scalar_one()
24
25 return f"{one} {two}"
26
27
28 sqlalchemy_config = SQLAlchemyAsyncConfig(connection_string="sqlite+aiosqlite:///test.sqlite")
29
30 app = Litestar(
31 route_handlers=[async_sqlalchemy_init],
32 plugins=[SQLAlchemyInitPlugin(config=sqlalchemy_config)],
33 )