Debian Codegraph @

docs/examples/data_transfer_objects/factory/tutorial/explicit_field_renaming.py

raw
1 from __future__ import annotations
2
3 from dataclasses import dataclass
4 from typing import List
5
6 from litestar import Litestar, get
7 from litestar.dto import DataclassDTO, DTOConfig
8 from litestar.params import FromPath
9
10
11 @dataclass
12 class Address:
13 street: str
14 city: str
15 country: str
16
17
18 @dataclass
19 class Person:
20 name: str
21 age: int
22 email: str
23 address: Address
24 children: List[Person]
25
26
27 class ReadDTO(DataclassDTO[Person]):
28 config = DTOConfig(
29 exclude={"email", "address.street", "children.0.email", "children.0.address"},
30 rename_fields={"address": "location"},
31 )
32
33
34 @get("/person/{name:str}", return_dto=ReadDTO, sync_to_thread=False)
35 def get_person(name: FromPath[str]) -> Person:
36 # Your logic to retrieve the person goes here
37 # For demonstration purposes, a placeholder Person instance is returned
38 address = Address(street="123 Main St", city="Cityville", country="Countryland")
39 child1 = Person(name="Child1", age=10, email="[email protected]", address=address, children=[])
40 child2 = Person(name="Child2", age=8, email="[email protected]", address=address, children=[])
41 return Person(
42 name=name,
43 age=30,
44 email=f"email_of_{name}@example.com",
45 address=address,
46 children=[child1, child2],
47 )
48
49
50 app = Litestar(route_handlers=[get_person])