| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from dataclasses import dataclass |
| 4 |
|
| 5 |
from litestar import Controller, Litestar, patch, post, put |
| 6 |
from litestar.dto import DataclassDTO, DTOConfig, DTOData |
| 7 |
from litestar.params import FromPath |
| 8 |
|
| 9 |
|
| 10 |
@dataclass |
| 11 |
class Person: |
| 12 |
name: str |
| 13 |
age: int |
| 14 |
email: str |
| 15 |
id: int |
| 16 |
|
| 17 |
|
| 18 |
class ReadDTO(DataclassDTO[Person]): |
| 19 |
config = DTOConfig(exclude={"email"}) |
| 20 |
|
| 21 |
|
| 22 |
class WriteDTO(DataclassDTO[Person]): |
| 23 |
config = DTOConfig(exclude={"id"}) |
| 24 |
|
| 25 |
|
| 26 |
class PatchDTO(DataclassDTO[Person]): |
| 27 |
config = DTOConfig(exclude={"id"}, partial=True) |
| 28 |
|
| 29 |
|
| 30 |
class PersonController(Controller): |
| 31 |
dto = WriteDTO |
| 32 |
return_dto = ReadDTO |
| 33 |
|
| 34 |
@post("/person", sync_to_thread=False) |
| 35 |
def create_person(self, data: DTOData[Person]) -> Person: |
| 36 |
# Logic for persisting the person goes here |
| 37 |
return data.create_instance(id=1) |
| 38 |
|
| 39 |
@put("/person/{person_id:int}", sync_to_thread=False) |
| 40 |
def update_person(self, person_id: FromPath[int], data: DTOData[Person]) -> Person: |
| 41 |
# Usually the Person would be retrieved from a database |
| 42 |
person = Person(id=person_id, name="John", age=50, email="[email protected]") |
| 43 |
return data.update_instance(person) |
| 44 |
|
| 45 |
@patch("/person/{person_id:int}", dto=PatchDTO, sync_to_thread=False) |
| 46 |
def patch_person(self, person_id: FromPath[int], data: DTOData[Person]) -> Person: |
| 47 |
# Usually the Person would be retrieved from a database |
| 48 |
person = Person(id=person_id, name="John", age=50, email="[email protected]") |
| 49 |
return data.update_instance(person) |
| 50 |
|
| 51 |
|
| 52 |
app = Litestar(route_handlers=[PersonController]) |