Debian Codegraph @

docs/examples/contrib/sqlalchemy/plugins/tutorial/full_app_with_serialization_plugin.py

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