| 1 |
from contextlib import asynccontextmanager |
| 2 |
from typing import Any, AsyncGenerator, Dict, List, Optional |
| 3 |
|
| 4 |
from sqlalchemy import select |
| 5 |
from sqlalchemy.exc import IntegrityError, NoResultFound |
| 6 |
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine |
| 7 |
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column |
| 8 |
|
| 9 |
from litestar import Litestar, get, post, put |
| 10 |
from litestar.datastructures import State |
| 11 |
from litestar.di import NamedDependency |
| 12 |
from litestar.exceptions import ClientException, NotFoundException |
| 13 |
from litestar.params import FromPath, FromQuery |
| 14 |
from litestar.status_codes import HTTP_409_CONFLICT |
| 15 |
|
| 16 |
TodoType = Dict[str, Any] |
| 17 |
TodoCollectionType = List[TodoType] |
| 18 |
|
| 19 |
|
| 20 |
class Base(DeclarativeBase): ... |
| 21 |
|
| 22 |
|
| 23 |
class TodoItem(Base): |
| 24 |
__tablename__ = "todo_items" |
| 25 |
|
| 26 |
title: Mapped[str] = mapped_column(primary_key=True) |
| 27 |
done: Mapped[bool] |
| 28 |
|
| 29 |
|
| 30 |
@asynccontextmanager |
| 31 |
async def db_connection(app: Litestar) -> AsyncGenerator[None, None]: |
| 32 |
engine = getattr(app.state, "engine", None) |
| 33 |
if engine is None: |
| 34 |
engine = create_async_engine("sqlite+aiosqlite:///todo.sqlite") |
| 35 |
app.state.engine = engine |
| 36 |
|
| 37 |
async with engine.begin() as conn: |
| 38 |
await conn.run_sync(Base.metadata.create_all) |
| 39 |
|
| 40 |
try: |
| 41 |
yield |
| 42 |
finally: |
| 43 |
await engine.dispose() |
| 44 |
|
| 45 |
|
| 46 |
sessionmaker = async_sessionmaker(expire_on_commit=False) |
| 47 |
|
| 48 |
|
| 49 |
async def provide_transaction(state: State) -> AsyncGenerator[AsyncSession, None]: |
| 50 |
async with sessionmaker(bind=state.engine) as session: |
| 51 |
try: |
| 52 |
async with session.begin(): |
| 53 |
yield session |
| 54 |
except IntegrityError as exc: |
| 55 |
raise ClientException( |
| 56 |
status_code=HTTP_409_CONFLICT, |
| 57 |
detail=str(exc), |
| 58 |
) from exc |
| 59 |
|
| 60 |
|
| 61 |
def serialize_todo(todo: TodoItem) -> TodoType: |
| 62 |
return {"title": todo.title, "done": todo.done} |
| 63 |
|
| 64 |
|
| 65 |
async def get_todo_by_title(todo_name: FromPath[str], session: AsyncSession) -> TodoItem: |
| 66 |
query = select(TodoItem).where(TodoItem.title == todo_name) |
| 67 |
result = await session.execute(query) |
| 68 |
try: |
| 69 |
return result.scalar_one() |
| 70 |
except NoResultFound as e: |
| 71 |
raise NotFoundException(detail=f"TODO {todo_name!r} not found") from e |
| 72 |
|
| 73 |
|
| 74 |
async def get_todo_list(done: FromQuery[Optional[bool]], session: AsyncSession) -> List[TodoItem]: |
| 75 |
query = select(TodoItem) |
| 76 |
if done is not None: |
| 77 |
query = query.where(TodoItem.done.is_(done)) |
| 78 |
|
| 79 |
result = await session.execute(query) |
| 80 |
return result.scalars().all() |
| 81 |
|
| 82 |
|
| 83 |
@get("/") |
| 84 |
async def get_list( |
| 85 |
transaction: NamedDependency[AsyncSession], done: FromQuery[Optional[bool]] = None |
| 86 |
) -> TodoCollectionType: |
| 87 |
return [serialize_todo(todo) for todo in await get_todo_list(done, transaction)] |
| 88 |
|
| 89 |
|
| 90 |
@post("/") |
| 91 |
async def add_item(data: TodoType, transaction: NamedDependency[AsyncSession]) -> TodoType: |
| 92 |
new_todo = TodoItem(title=data["title"], done=data["done"]) |
| 93 |
transaction.add(new_todo) |
| 94 |
return serialize_todo(new_todo) |
| 95 |
|
| 96 |
|
| 97 |
@put("/{item_title:str}") |
| 98 |
async def update_item( |
| 99 |
item_title: FromPath[str], data: TodoType, transaction: NamedDependency[AsyncSession] |
| 100 |
) -> TodoType: |
| 101 |
todo_item = await get_todo_by_title(item_title, transaction) |
| 102 |
todo_item.title = data["title"] |
| 103 |
todo_item.done = data["done"] |
| 104 |
return serialize_todo(todo_item) |
| 105 |
|
| 106 |
|
| 107 |
app = Litestar( |
| 108 |
[get_list, add_item, update_item], |
| 109 |
dependencies={"transaction": provide_transaction}, |
| 110 |
lifespan=[db_connection], |
| 111 |
) |