| 1 |
from contextlib import asynccontextmanager |
| 2 |
from typing import Any, AsyncGenerator, Dict, List, Optional, Sequence |
| 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.exceptions import ClientException, NotFoundException |
| 12 |
from litestar.params import FromPath, FromQuery |
| 13 |
from litestar.status_codes import HTTP_409_CONFLICT |
| 14 |
|
| 15 |
TodoType = Dict[str, Any] |
| 16 |
TodoCollectionType = List[TodoType] |
| 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 |
@asynccontextmanager |
| 30 |
async def db_connection(app: Litestar) -> AsyncGenerator[None, None]: |
| 31 |
engine = getattr(app.state, "engine", None) |
| 32 |
if engine is None: |
| 33 |
engine = create_async_engine("sqlite+aiosqlite:///todo.sqlite", echo=True) |
| 34 |
app.state.engine = engine |
| 35 |
|
| 36 |
async with engine.begin() as conn: |
| 37 |
await conn.run_sync(Base.metadata.create_all) |
| 38 |
|
| 39 |
try: |
| 40 |
yield |
| 41 |
finally: |
| 42 |
await engine.dispose() |
| 43 |
|
| 44 |
|
| 45 |
sessionmaker = async_sessionmaker(expire_on_commit=False) |
| 46 |
|
| 47 |
|
| 48 |
def serialize_todo(todo: TodoItem) -> TodoType: |
| 49 |
return {"title": todo.title, "done": todo.done} |
| 50 |
|
| 51 |
|
| 52 |
async def get_todo_by_title(todo_name: FromPath[str], session: AsyncSession) -> TodoItem: |
| 53 |
query = select(TodoItem).where(TodoItem.title == todo_name) |
| 54 |
result = await session.execute(query) |
| 55 |
try: |
| 56 |
return result.scalar_one() |
| 57 |
except NoResultFound as e: |
| 58 |
raise NotFoundException(detail=f"TODO {todo_name!r} not found") from e |
| 59 |
|
| 60 |
|
| 61 |
async def get_todo_list(done: FromQuery[Optional[bool]], session: AsyncSession) -> Sequence[TodoItem]: |
| 62 |
query = select(TodoItem) |
| 63 |
if done is not None: |
| 64 |
query = query.where(TodoItem.done.is_(done)) |
| 65 |
|
| 66 |
result = await session.execute(query) |
| 67 |
return result.scalars().all() |
| 68 |
|
| 69 |
|
| 70 |
@get("/") |
| 71 |
async def get_list(state: State, done: FromQuery[Optional[bool]] = None) -> TodoCollectionType: |
| 72 |
async with sessionmaker(bind=state.engine) as session: |
| 73 |
return [serialize_todo(todo) for todo in await get_todo_list(done, session)] |
| 74 |
|
| 75 |
|
| 76 |
@post("/") |
| 77 |
async def add_item(data: TodoType, state: State) -> TodoType: |
| 78 |
new_todo = TodoItem(title=data["title"], done=data["done"]) |
| 79 |
async with sessionmaker(bind=state.engine) as session: |
| 80 |
try: |
| 81 |
async with session.begin(): |
| 82 |
session.add(new_todo) |
| 83 |
except IntegrityError as e: |
| 84 |
raise ClientException( |
| 85 |
status_code=HTTP_409_CONFLICT, |
| 86 |
detail=f"TODO {new_todo.title!r} already exists", |
| 87 |
) from e |
| 88 |
|
| 89 |
return serialize_todo(new_todo) |
| 90 |
|
| 91 |
|
| 92 |
@put("/{item_title:str}") |
| 93 |
async def update_item(item_title: FromPath[str], data: TodoType, state: State) -> TodoType: |
| 94 |
async with sessionmaker(bind=state.engine) as session, session.begin(): |
| 95 |
todo_item = await get_todo_by_title(item_title, session) |
| 96 |
todo_item.title = data["title"] |
| 97 |
todo_item.done = data["done"] |
| 98 |
return serialize_todo(todo_item) |
| 99 |
|
| 100 |
|
| 101 |
app = Litestar([get_list, add_item, update_item], lifespan=[db_connection]) |