| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from typing import TYPE_CHECKING |
| 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, SQLAlchemyInitPlugin |
| 11 |
|
| 12 |
if TYPE_CHECKING: |
| 13 |
from typing import Any, Dict, List |
| 14 |
|
| 15 |
from sqlalchemy.ext.asyncio import AsyncSession |
| 16 |
|
| 17 |
|
| 18 |
class Base(DeclarativeBase): ... |
| 19 |
|
| 20 |
|
| 21 |
class TodoItem(Base): |
| 22 |
__tablename__ = "todo_item" |
| 23 |
title: Mapped[str] = mapped_column(primary_key=True) |
| 24 |
done: Mapped[bool] |
| 25 |
|
| 26 |
|
| 27 |
@post("/") |
| 28 |
async def add_item(data: Dict[str, Any], db_session: NamedDependency[AsyncSession]) -> List[Dict[str, Any]]: |
| 29 |
todo_item = TodoItem(**data) |
| 30 |
async with db_session.begin(): |
| 31 |
db_session.add(todo_item) |
| 32 |
return [ |
| 33 |
{ |
| 34 |
"title": item.title, |
| 35 |
"done": item.done, |
| 36 |
} |
| 37 |
for item in (await db_session.execute(select(TodoItem))).scalars() |
| 38 |
] |
| 39 |
|
| 40 |
|
| 41 |
async def init_db(app: Litestar) -> None: |
| 42 |
async with config.get_engine().begin() as conn: |
| 43 |
await conn.run_sync(Base.metadata.create_all) |
| 44 |
|
| 45 |
|
| 46 |
config = SQLAlchemyAsyncConfig(connection_string="sqlite+aiosqlite:///todo_async.sqlite") |
| 47 |
plugin = SQLAlchemyInitPlugin(config=config) |
| 48 |
app = Litestar(route_handlers=[add_item], plugins=[plugin], on_startup=[init_db], debug=True) |