| 1 |
from typing import AsyncGenerator, List, Optional |
| 2 |
|
| 3 |
from sqlalchemy import select |
| 4 |
from sqlalchemy.exc import IntegrityError, NoResultFound |
| 5 |
from sqlalchemy.ext.asyncio import AsyncSession |
| 6 |
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column |
| 7 |
|
| 8 |
from litestar import Litestar, get, post, put |
| 9 |
from litestar.exceptions import ClientException, NotFoundException |
| 10 |
from litestar.params import FromPath, FromQuery |
| 11 |
from litestar.plugins.sqlalchemy import ( |
| 12 |
SQLAlchemyAsyncConfig, |
| 13 |
SQLAlchemyInitPlugin, |
| 14 |
SQLAlchemySerializationPlugin, |
| 15 |
) |
| 16 |
from litestar.status_codes import HTTP_409_CONFLICT |
| 17 |
|
| 18 |
|
| 19 |
class Base(DeclarativeBase): ... |
| 20 |
|
| 21 |
|
| 22 |
class TodoItem(Base): |
| 23 |
__tablename__ = "todo_items" |
| 24 |
|
| 25 |
title: Mapped[str] = mapped_column(primary_key=True) |
| 26 |
done: Mapped[bool] |
| 27 |
|
| 28 |
|
| 29 |
async def provide_transaction(db_session: AsyncSession) -> AsyncGenerator[AsyncSession, None]: |
| 30 |
try: |
| 31 |
async with db_session.begin(): |
| 32 |
yield db_session |
| 33 |
except IntegrityError as exc: |
| 34 |
raise ClientException( |
| 35 |
status_code=HTTP_409_CONFLICT, |
| 36 |
detail=str(exc), |
| 37 |
) from exc |
| 38 |
|
| 39 |
|
| 40 |
async def get_todo_by_title(todo_name: FromPath[str], session: AsyncSession) -> TodoItem: |
| 41 |
query = select(TodoItem).where(TodoItem.title == todo_name) |
| 42 |
result = await session.execute(query) |
| 43 |
try: |
| 44 |
return result.scalar_one() |
| 45 |
except NoResultFound as e: |
| 46 |
raise NotFoundException(detail=f"TODO {todo_name!r} not found") from e |
| 47 |
|
| 48 |
|
| 49 |
async def get_todo_list(done: FromQuery[Optional[bool]], session: AsyncSession) -> List[TodoItem]: |
| 50 |
query = select(TodoItem) |
| 51 |
if done is not None: |
| 52 |
query = query.where(TodoItem.done.is_(done)) |
| 53 |
|
| 54 |
result = await session.execute(query) |
| 55 |
return list(result.scalars().all()) |
| 56 |
|
| 57 |
|
| 58 |
@get("/") |
| 59 |
async def get_list(transaction: AsyncSession, done: FromQuery[Optional[bool]] = None) -> List[TodoItem]: |
| 60 |
return await get_todo_list(done, transaction) |
| 61 |
|
| 62 |
|
| 63 |
@post("/") |
| 64 |
async def add_item(data: TodoItem, transaction: AsyncSession) -> TodoItem: |
| 65 |
transaction.add(data) |
| 66 |
return data |
| 67 |
|
| 68 |
|
| 69 |
@put("/{item_title:str}") |
| 70 |
async def update_item(item_title: FromPath[str], data: TodoItem, transaction: AsyncSession) -> TodoItem: |
| 71 |
todo_item = await get_todo_by_title(item_title, transaction) |
| 72 |
todo_item.title = data.title |
| 73 |
todo_item.done = data.done |
| 74 |
return todo_item |
| 75 |
|
| 76 |
|
| 77 |
db_config = SQLAlchemyAsyncConfig( |
| 78 |
connection_string="sqlite+aiosqlite:///todo.sqlite", metadata=Base.metadata, create_all=True |
| 79 |
) |
| 80 |
|
| 81 |
app = Litestar( |
| 82 |
[get_list, add_item, update_item], |
| 83 |
dependencies={"transaction": provide_transaction}, |
| 84 |
plugins=[ |
| 85 |
SQLAlchemySerializationPlugin(), |
| 86 |
SQLAlchemyInitPlugin(db_config), |
| 87 |
], |
| 88 |
) |