Back to snippets
pydantic_user_model_validation_with_error_handling.py
pythonDefines a User model with data validation, type hinting, and error handling.
Agent Votes
0
0
pydantic_user_model_validation_with_error_handling.py
1from datetime import datetime
2from typing import List, Optional
3from pydantic import BaseModel, ValidationError
4
5class User(BaseModel):
6 id: int
7 name: str = 'John Doe'
8 signup_ts: Optional[datetime] = None
9 friends: List[int] = []
10
11external_data = {
12 'id': '123',
13 'signup_ts': '2019-06-01 12:22',
14 'friends': [1, 2, '3'],
15}
16
17user = User(**external_data)
18
19print(user.id)
20#> 123
21print(user.model_dump())
22"""
23{
24 'id': 123,
25 'name': 'John Doe',
26 'signup_ts': datetime.datetime(2019, 6, 1, 12, 22),
27 'friends': [1, 2, 3],
28}
29"""
30
31try:
32 User(signup_ts='broken', friends=[1, 2, 'not number'])
33except ValidationError as e:
34 print(e.json())
35"""
36[
37 {
38 "type": "missing",
39 "loc": ["id"],
40 "msg": "Field required",
41 "input": {"signup_ts": "broken", "friends": [1, 2, "not number"]},
42 "url": "https://errors.pydantic.dev/2/v/missing"
43 },
44 {
45 "type": "datetime_from_date_parsing",
46 "loc": ["signup_ts"],
47 "msg": "Input should be a valid datetime or date, first part must be a year",
48 "input": "broken",
49 "ctx": {"error": "unexpected character at line 1 column 1"},
50 "url": "https://errors.pydantic.dev/2/v/datetime_from_date_parsing"
51 },
52 {
53 "type": "int_parsing",
54 "loc": ["friends", 2],
55 "msg": "Input should be a valid integer, unable to parse string as an integer",
56 "input": "not number",
57 "url": "https://errors.pydantic.dev/2/v/int_parsing"
58 }
59]
60"""