Debian Codegraph @

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

raw
1 from __future__ import annotations
2
3 from typing import TYPE_CHECKING, Sequence
4
5 from sqlalchemy import select
6 from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
7
8 from litestar import Litestar, post
9 from litestar.di import NamedDependency
10 from litestar.plugins.sqlalchemy import SQLAlchemyAsyncConfig, SQLAlchemyPlugin
11
12 if TYPE_CHECKING:
13 from sqlalchemy.ext.asyncio import AsyncSession
14
15
16 class Base(DeclarativeBase): ...
17
18
19 class TodoItem(Base):
20 __tablename__ = "todo_item"
21 title: Mapped[str] = mapped_column(primary_key=True)
22 done: Mapped[bool]
23
24
25 @post("/")
26 async def add_item(data: TodoItem, db_session: NamedDependency[AsyncSession]) -> Sequence[TodoItem]:
27 async with db_session.begin():
28 db_session.add(data)
29 return (await db_session.execute(select(TodoItem))).scalars().all()
30
31
32 config = SQLAlchemyAsyncConfig(
33 connection_string="sqlite+aiosqlite:///todo_async.sqlite", create_all=True, metadata=Base.metadata
34 )
35 plugin = SQLAlchemyPlugin(config=config)
36 app = Litestar(route_handlers=[add_item], plugins=[plugin])