| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from dataclasses import dataclass |
| 4 |
from uuid import UUID |
| 5 |
|
| 6 |
from litestar import Litestar, patch |
| 7 |
from litestar.dto import DataclassDTO, DTOConfig, DTOData |
| 8 |
from litestar.params import FromPath |
| 9 |
|
| 10 |
|
| 11 |
@dataclass |
| 12 |
class Person: |
| 13 |
id: UUID |
| 14 |
name: str |
| 15 |
age: int |
| 16 |
|
| 17 |
|
| 18 |
class PatchDTO(DataclassDTO[Person]): |
| 19 |
"""Don't allow client to set the id, and allow partial updates.""" |
| 20 |
|
| 21 |
config = DTOConfig(exclude={"id"}, partial=True) |
| 22 |
|
| 23 |
|
| 24 |
peter_uuid = UUID("f32ff2ce-e32f-4537-9dc0-26e7599f1380") |
| 25 |
database = {peter_uuid: Person(id=peter_uuid, name="Peter", age=40)} |
| 26 |
|
| 27 |
|
| 28 |
@patch("/person/{person_id:uuid}", dto=PatchDTO, return_dto=None, sync_to_thread=False) |
| 29 |
def update_person(person_id: FromPath[UUID], data: DTOData[Person]) -> Person: |
| 30 |
"""Partially update a person.""" |
| 31 |
return data.update_instance(database[person_id]) |
| 32 |
|
| 33 |
|
| 34 |
app = Litestar(route_handlers=[update_person]) |
| 35 |
|
| 36 |
# run: /person/f32ff2ce-e32f-4537-9dc0-26e7599f1380 -X PATCH -H "Content-Type: application/json" -d '{"name":"Peter Pan"}' |