-
Notifications
You must be signed in to change notification settings - Fork 1
/
schemas.py
76 lines (67 loc) · 2.43 KB
/
schemas.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
from pydantic import BaseModel, ConfigDict, Field, model_validator
not_required_fields = [
"description",
"price",
"variety",
"winery",
"designation",
"country",
"province",
"region_1",
"region_2",
"taster_name",
"taster_twitter_handle",
]
class Wine(BaseModel):
model_config = ConfigDict(
populate_by_name=True,
str_strip_whitespace=True,
)
id: int
points: int
title: str
description: str | None
price: float | None
variety: str | None
winery: str | None
designation: str | None = Field(None, alias="vineyard")
country: str | None
province: str | None
region_1: str | None
region_2: str | None
taster_name: str | None
taster_twitter_handle: str | None
@model_validator(mode="before")
def _remove_unknowns(cls, values):
"Set other fields that have the value 'null' as None so that we can throw it away"
for field in not_required_fields:
if not values.get(field) or values.get(field) == "null":
values[field] = None
return values
@model_validator(mode="before")
def _fill_country_unknowns(cls, values):
"Fill in missing country values with 'Unknown', as we always want this field to be queryable"
country = values.get("country")
if not country or country == "null":
values["country"] = "Unknown"
return values
if __name__ == "__main__":
sample_data = {
"id": 45100,
"points": 85.0, # Intentionally not an int to test coercion
"title": "Balduzzi 2012 Reserva Merlot (Maule Valley)",
"description": "Ripe in color and aromas, this chunky wine delivers heavy baked-berry and raisin aromas in front of a jammy, extracted palate. Raisin and cooked berry flavors finish plump, with earthy notes.",
"price": 10, # Intentionally not a float to test coercion
"variety": "Merlot",
"winery": "Balduzzi",
"country": "null", # Test null handling with 'Unknown' fallback
"province": "Maule Valley",
"region_1": "null", # Test null handling
# "region_2": "null" # Test missing value handling
"taster_name": "Michael Schachner",
"taster_twitter_handle": "@wineschach",
"designation": " The Vineyard ",
}
wine = Wine(**sample_data)
from pprint import pprint
pprint(wine.model_dump(exclude_none=True), sort_dicts=False)