| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from datetime import date |
| 4 |
from typing import TYPE_CHECKING, Annotated |
| 5 |
from uuid import UUID |
| 6 |
|
| 7 |
from pydantic import BaseModel as _BaseModel |
| 8 |
from pydantic import TypeAdapter |
| 9 |
from sqlalchemy import ForeignKey, select |
| 10 |
from sqlalchemy.orm import Mapped, mapped_column, relationship, selectinload |
| 11 |
|
| 12 |
from litestar import Litestar, get |
| 13 |
from litestar.controller import Controller |
| 14 |
from litestar.di import Provide |
| 15 |
from litestar.handlers.http_handlers.decorators import delete, patch, post |
| 16 |
from litestar.pagination import OffsetPagination |
| 17 |
from litestar.params import PathParameter, QueryParameter |
| 18 |
from litestar.plugins.sqlalchemy import ( |
| 19 |
AsyncSessionConfig, |
| 20 |
SQLAlchemyAsyncConfig, |
| 21 |
SQLAlchemyInitPlugin, |
| 22 |
base, |
| 23 |
filters, |
| 24 |
repository, |
| 25 |
) |
| 26 |
|
| 27 |
if TYPE_CHECKING: |
| 28 |
from sqlalchemy.ext.asyncio import AsyncSession |
| 29 |
|
| 30 |
|
| 31 |
class BaseModel(_BaseModel): |
| 32 |
"""Extend Pydantic's BaseModel to enable ORM mode""" |
| 33 |
|
| 34 |
model_config = {"from_attributes": True} |
| 35 |
|
| 36 |
|
| 37 |
# The SQLAlchemy base includes a declarative model for you to use in your models. |
| 38 |
# The `UUIDBase` class includes a `UUID` based primary key (`id`) |
| 39 |
class AuthorModel(base.UUIDBase): |
| 40 |
# we can optionally provide the table name instead of auto-generating it |
| 41 |
__tablename__ = "author" # type: ignore[assignment] |
| 42 |
name: Mapped[str] |
| 43 |
dob: Mapped[date | None] |
| 44 |
books: Mapped[list[BookModel]] = relationship(back_populates="author", lazy="noload") |
| 45 |
|
| 46 |
|
| 47 |
# The `UUIDAuditBase` class includes the same UUID` based primary key (`id`) and 2 |
| 48 |
# additional columns: `created_at` and `updated_at`. `created_at` is a timestamp of when the |
| 49 |
# record created, and `updated_at` is the last time the record was modified. |
| 50 |
class BookModel(base.UUIDAuditBase): |
| 51 |
__tablename__ = "book" # type: ignore[assignment] |
| 52 |
title: Mapped[str] |
| 53 |
author_id: Mapped[UUID] = mapped_column(ForeignKey("author.id")) |
| 54 |
author: Mapped[AuthorModel] = relationship(lazy="joined", innerjoin=True, viewonly=True) |
| 55 |
|
| 56 |
|
| 57 |
# we will explicitly define the schema instead of using DTO objects for clarity. |
| 58 |
|
| 59 |
|
| 60 |
class Author(BaseModel): |
| 61 |
id: UUID | None |
| 62 |
name: str |
| 63 |
dob: date | None = None |
| 64 |
|
| 65 |
|
| 66 |
class AuthorCreate(BaseModel): |
| 67 |
name: str |
| 68 |
dob: date | None = None |
| 69 |
|
| 70 |
|
| 71 |
class AuthorUpdate(BaseModel): |
| 72 |
name: str | None = None |
| 73 |
dob: date | None = None |
| 74 |
|
| 75 |
|
| 76 |
class AuthorRepository(repository.SQLAlchemyAsyncRepository[AuthorModel]): |
| 77 |
"""Author repository.""" |
| 78 |
|
| 79 |
model_type = AuthorModel |
| 80 |
|
| 81 |
|
| 82 |
async def provide_authors_repo(db_session: AsyncSession) -> AuthorRepository: |
| 83 |
"""This provides the default Authors repository.""" |
| 84 |
return AuthorRepository(session=db_session) |
| 85 |
|
| 86 |
|
| 87 |
# we can optionally override the default `select` used for the repository to pass in |
| 88 |
# specific SQL options such as join details |
| 89 |
async def provide_author_details_repo(db_session: AsyncSession) -> AuthorRepository: |
| 90 |
"""This provides a simple example demonstrating how to override the join options for the repository.""" |
| 91 |
return AuthorRepository( |
| 92 |
statement=select(AuthorModel).options(selectinload(AuthorModel.books)), |
| 93 |
session=db_session, |
| 94 |
) |
| 95 |
|
| 96 |
|
| 97 |
def provide_limit_offset_pagination( |
| 98 |
current_page: Annotated[int, QueryParameter(name="currentPage", ge=1, required=False)] = 1, |
| 99 |
page_size: Annotated[int, QueryParameter(name="pageSize", ge=1, required=False)] = 10, |
| 100 |
) -> filters.LimitOffset: |
| 101 |
"""Add offset/limit pagination. |
| 102 |
|
| 103 |
Return type consumed by `Repository.apply_limit_offset_pagination()`. |
| 104 |
|
| 105 |
Parameters |
| 106 |
---------- |
| 107 |
current_page : int |
| 108 |
LIMIT to apply to select. |
| 109 |
page_size : int |
| 110 |
OFFSET to apply to select. |
| 111 |
""" |
| 112 |
return filters.LimitOffset(page_size, page_size * (current_page - 1)) |
| 113 |
|
| 114 |
|
| 115 |
class AuthorController(Controller): |
| 116 |
"""Author CRUD""" |
| 117 |
|
| 118 |
dependencies = {"authors_repo": Provide(provide_authors_repo)} |
| 119 |
|
| 120 |
@get(path="/authors") |
| 121 |
async def list_authors( |
| 122 |
self, |
| 123 |
authors_repo: AuthorRepository, |
| 124 |
limit_offset: filters.LimitOffset, |
| 125 |
) -> OffsetPagination[Author]: |
| 126 |
"""List authors.""" |
| 127 |
results, total = await authors_repo.list_and_count(limit_offset) |
| 128 |
type_adapter = TypeAdapter(list[Author]) |
| 129 |
return OffsetPagination[Author]( |
| 130 |
items=type_adapter.validate_python(results), |
| 131 |
total=total, |
| 132 |
limit=limit_offset.limit, |
| 133 |
offset=limit_offset.offset, |
| 134 |
) |
| 135 |
|
| 136 |
@post(path="/authors") |
| 137 |
async def create_author( |
| 138 |
self, |
| 139 |
authors_repo: AuthorRepository, |
| 140 |
data: AuthorCreate, |
| 141 |
) -> Author: |
| 142 |
"""Create a new author.""" |
| 143 |
obj = await authors_repo.add( |
| 144 |
AuthorModel(**data.model_dump(exclude_unset=True, exclude_none=True)), |
| 145 |
) |
| 146 |
await authors_repo.session.commit() |
| 147 |
return Author.model_validate(obj) |
| 148 |
|
| 149 |
# we override the authors_repo to use the version that joins the Books in |
| 150 |
@get(path="/authors/{author_id:uuid}", dependencies={"authors_repo": Provide(provide_author_details_repo)}) |
| 151 |
async def get_author( |
| 152 |
self, |
| 153 |
authors_repo: AuthorRepository, |
| 154 |
author_id: Annotated[ |
| 155 |
UUID, |
| 156 |
PathParameter( |
| 157 |
title="Author ID", |
| 158 |
description="The author to retrieve.", |
| 159 |
), |
| 160 |
], |
| 161 |
) -> Author: |
| 162 |
"""Get an existing author.""" |
| 163 |
obj = await authors_repo.get(author_id) |
| 164 |
return Author.model_validate(obj) |
| 165 |
|
| 166 |
@patch( |
| 167 |
path="/authors/{author_id:uuid}", |
| 168 |
dependencies={"authors_repo": Provide(provide_author_details_repo)}, |
| 169 |
) |
| 170 |
async def update_author( |
| 171 |
self, |
| 172 |
authors_repo: AuthorRepository, |
| 173 |
data: AuthorUpdate, |
| 174 |
author_id: Annotated[ |
| 175 |
UUID, |
| 176 |
PathParameter( |
| 177 |
title="Author ID", |
| 178 |
description="The author to update.", |
| 179 |
), |
| 180 |
], |
| 181 |
) -> Author: |
| 182 |
"""Update an author.""" |
| 183 |
raw_obj = data.model_dump(exclude_unset=True, exclude_none=True) |
| 184 |
raw_obj.update({"id": author_id}) |
| 185 |
obj = await authors_repo.update(AuthorModel(**raw_obj)) |
| 186 |
await authors_repo.session.commit() |
| 187 |
return Author.from_orm(obj) |
| 188 |
|
| 189 |
@delete(path="/authors/{author_id:uuid}") |
| 190 |
async def delete_author( |
| 191 |
self, |
| 192 |
authors_repo: AuthorRepository, |
| 193 |
author_id: Annotated[ |
| 194 |
UUID, |
| 195 |
PathParameter( |
| 196 |
title="Author ID", |
| 197 |
description="The author to delete.", |
| 198 |
), |
| 199 |
], |
| 200 |
) -> None: |
| 201 |
"""Delete a author from the system.""" |
| 202 |
_ = await authors_repo.delete(author_id) |
| 203 |
await authors_repo.session.commit() |
| 204 |
|
| 205 |
|
| 206 |
session_config = AsyncSessionConfig(expire_on_commit=False) |
| 207 |
sqlalchemy_config = SQLAlchemyAsyncConfig( |
| 208 |
connection_string="sqlite+aiosqlite:///test.sqlite", session_config=session_config |
| 209 |
) # Create 'db_session' dependency. |
| 210 |
sqlalchemy_plugin = SQLAlchemyInitPlugin(config=sqlalchemy_config) |
| 211 |
|
| 212 |
|
| 213 |
async def on_startup() -> None: |
| 214 |
"""Initializes the database.""" |
| 215 |
async with sqlalchemy_config.get_engine().begin() as conn: |
| 216 |
await conn.run_sync(base.UUIDBase.metadata.create_all) |
| 217 |
|
| 218 |
|
| 219 |
app = Litestar( |
| 220 |
route_handlers=[AuthorController], |
| 221 |
on_startup=[on_startup], |
| 222 |
plugins=[SQLAlchemyInitPlugin(config=sqlalchemy_config)], |
| 223 |
dependencies={"limit_offset": Provide(provide_limit_offset_pagination)}, |
| 224 |
) |