| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from typing import TYPE_CHECKING, Sequence |
| 4 |
|
| 5 |
from sqlalchemy import select |
| 6 |
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column |
| 7 |
|
| 8 |
from litestar import Litestar, post |
| 9 |
from litestar.di import NamedDependency |
| 10 |
from litestar.plugins.sqlalchemy import SQLAlchemyPlugin, SQLAlchemySyncConfig |
| 11 |
|
| 12 |
if TYPE_CHECKING: |
| 13 |
from sqlalchemy.orm import Session |
| 14 |
|
| 15 |
|
| 16 |
class Base(DeclarativeBase): ... |
| 17 |
|
| 18 |
|
| 19 |
class TodoItem(Base): |
| 20 |
__tablename__ = "todo_item" |
| 21 |
title: Mapped[str] = mapped_column(primary_key=True) |
| 22 |
done: Mapped[bool] |
| 23 |
|
| 24 |
|
| 25 |
@post("/", sync_to_thread=True) |
| 26 |
def add_item(data: TodoItem, db_session: NamedDependency[Session]) -> Sequence[TodoItem]: |
| 27 |
with db_session.begin(): |
| 28 |
db_session.add(data) |
| 29 |
return db_session.execute(select(TodoItem)).scalars().all() |
| 30 |
|
| 31 |
|
| 32 |
config = SQLAlchemySyncConfig(connection_string="sqlite:///todo_sync.sqlite", create_all=True, metadata=Base.metadata) |
| 33 |
plugin = SQLAlchemyPlugin(config=config) |
| 34 |
app = Litestar(route_handlers=[add_item], plugins=[plugin]) |