Skip to content

Commit 45edabb

Browse files
authored
Update examples.py
1 parent ed7d8cb commit 45edabb

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

pydantic-for-python-devs/examples.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,42 @@ def parse_created_at(cls, v):
159159
user = UserProfile(**api_response.data)
160160
print(f"User {user.username} created at {user.created_at}")
161161

162+
from pydantic import BaseModel, ValidationError
163+
from typing import List
164+
165+
class Order(BaseModel):
166+
order_id: int
167+
customer_email: str
168+
items: List[str]
169+
total: float
170+
171+
@field_validator('total')
172+
def positive_total(cls, v):
173+
if v <= 0:
174+
raise ValueError('Total must be positive')
175+
return v
176+
177+
# Invalid data
178+
bad_data = {
179+
"order_id": "not_a_number",
180+
"customer_email": "invalid_email",
181+
"items": "should_be_list",
182+
"total": -10.50
183+
}
184+
185+
try:
186+
order = Order(**bad_data)
187+
except ValidationError as e:
188+
print("Validation errors:")
189+
for error in e.errors():
190+
field = error['loc'][0]
191+
message = error['msg']
192+
print(f" {field}: {message}")
193+
194+
# Get JSON representation of errors
195+
print("\nJSON errors:")
196+
print(e.json(indent=2))
197+
162198

163199
from pydantic import BaseModel
164200
from datetime import datetime

0 commit comments

Comments
 (0)