Debian Codegraph @

docs/examples/data_transfer_objects/factory/tutorial/nested_collection_exclude.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(exclude={"email", "address.street", "children.0.email", "children.0.address"})
29
30
31 @get("/person/{name:str}", return_dto=ReadDTO, sync_to_thread=False)
32 def get_person(name: FromPath[str]) -> Person:
33 # Your logic to retrieve the person goes here
34 # For demonstration purposes, a placeholder Person instance is returned
35 address = Address(street="123 Main St", city="Cityville", country="Countryland")
36 child1 = Person(name="Child1", age=10, email="[email protected]", address=address, children=[])
37 child2 = Person(name="Child2", age=8, email="[email protected]", address=address, children=[])
38 return Person(
39 name=name,
40 age=30,
41 email=f"email_of_{name}@example.com",
42 address=address,
43 children=[child1, child2],
44 )
45
46
47 app = Litestar(route_handlers=[get_person])