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