from uuid import UUID
from typing import Union
from pydantic import BaseModel
classUser(BaseModel):id: Union[UUID,int,str]
name:str
user_03_uuid = UUID('cf57432e-809e-4353-adbd-9d5c0d733868')
user_03 = User(id=user_03_uuid, name='John Doe')print(user_03)#> id=UUID('cf57432e-809e-4353-adbd-9d5c0d733868') name='John Doe'print(user_03.id)#> cf57432e-809e-4353-adbd-9d5c0d733868print(user_03_uuid.int)#> 275603287559914445491632874575877060712
2.限制复合型
Literal:需要python3.8
from typing import Literal, Union
from pydantic import BaseModel, Field, ValidationError
classCat(BaseModel):
pet_type: Literal['cat']
meows:intclassDog(BaseModel):
pet_type: Literal['dog']
barks:floatclassLizard(BaseModel):
pet_type: Literal['reptile','lizard']
scales:boolclassModel(BaseModel):# discriminator定义限制字段
pet: Union[Cat, Dog, Lizard]= Field(..., discriminator='pet_type')
n:intprint(Model(pet={'pet_type':'dog','barks':3.14}, n=1))try:
Model(pet={'pet_type':'dog'}, n=1)except ValidationError as e:print(e)"""
1 validation error for Model
pet -> Dog -> barks
field required (type=value_error.missing)
"""
3.嵌套限制复合型
from typing import Literal, Union
from typing_extensions import Annotated
from pydantic import BaseModel, Field, ValidationError
classBlackCat(BaseModel):
pet_type: Literal['cat']
color: Literal['black']
black_name:strclassWhiteCat(BaseModel):
pet_type: Literal['cat']
color: Literal['white']
white_name:str# Can also be written with a custom root type## class Cat(BaseModel):# __root__: Annotated[Union[BlackCat, WhiteCat], Field(discriminator='color')]
Cat = Annotated[Union[BlackCat, WhiteCat], Field(discriminator='color')]classDog(BaseModel):
pet_type: Literal['dog']
name:str
Pet = Annotated[Union[Cat, Dog], Field(discriminator='pet_type')]classModel(BaseModel):
pet: Pet
n:int
m = Model(pet={'pet_type':'cat','color':'black','black_name':'felix'}, n=1)print(m)#> pet=BlackCat(pet_type='cat', color='black', black_name='felix') n=1try:
Model(pet={'pet_type':'cat','color':'red'}, n='1')except ValidationError as e:print(e)"""
1 validation error for Model
pet -> Union[BlackCat, WhiteCat]
No match for discriminator 'color' and value 'red' (allowed values:
'black', 'white')
(type=value_error.discriminated_union.invalid_discriminator;
discriminator_key=color; discriminator_value=red; allowed_values='black',
'white')
"""try:
Model(pet={'pet_type':'cat','color':'black'}, n='1')except ValidationError as e:print(e)"""
1 validation error for Model
pet -> Union[BlackCat, WhiteCat] -> BlackCat -> black_name
field required (type=value_error.missing)
"""
4.枚举和选择
from enum import Enum, IntEnum
from pydantic import BaseModel, ValidationError
classFruitEnum(str, Enum):
pear ='pear'
banana ='banana'classToolEnum(IntEnum):
spanner =1
wrench =2classCookingModel(BaseModel):
fruit: FruitEnum = FruitEnum.pear
tool: ToolEnum = ToolEnum.spanner
print(CookingModel(tool=2, fruit='banana'))try:
CookingModel(fruit='other')except ValidationError as e:print(str(e))"""
1 validation error for CookingModel
fruit
value is not a valid enumeration member; permitted: 'pear', 'banana' (type=type_error.enum; enum_values=[<FruitEnum.pear: 'pear'>, <FruitEnum.banana: 'banana'>])
"""
from datetime import datetime, date
from pydantic import BaseModel
classModel(BaseModel):
d: date =None
d = datetime.now()# 将datetime转为str
str_d = dt.strftime('%Y-%m-%d')# 将datetime转为时间戳
d_stamp = datetime.timestamp(dt)
m = Model(d=d)# m = Model(d=d.date())# m = Model(d=str_d)# m = Model(d=d_stamp)print(m.json())
time:支持time对象、str
from datetime import datetime, time
from pydantic import BaseModel
classModel(BaseModel):
t: time =None
t = datetime.now().time()# 将datetime转为str
str_t = datetime.now().strftime('%H:%M:%S.%f')
m = Model(t=t)# m = Model(t=str_t)print(m.json())
timedelta:支持timedelta对象、str、int
from datetime import timedelta
from pydantic import BaseModel
classModel(BaseModel):
td: timedelta =None# timedelta
td = timedelta(days=1, hours=3, minutes=10)# str # [-][DD ][HH:MM]SS[.ffffff] | [±]P[DD]DT[HH]H[MM]M[SS]S# str_td = "P3DT12H30M5S"# str_td = "3 29:18:39"
str_td ="1 10:48:27.112324"# int
int_td =36000# m = Model(td=td)
m = Model(td=str_td)# m = Model(td=int_td)print(m.dict())
from pydantic import BaseModel, PyObject
classModel(BaseModel):
e: PyObject
m = Model(e="builtins.ord")print(m.e('a'))
Color:用于解析HTML和CSS颜色;请参阅颜色类型
Json:一个特殊的类型包装器,在解析之前加载JSON
PaymentCardNumber:用于解析和验证支付卡
AnyUrl:任何网址
AnyHttpUrl:一个 HTTP 网址
HttpUrl:更严格的HTTP网址
from pydantic import BaseModel, HttpUrl, PostgresDsn, ValidationError, validator
classMyModel(BaseModel):
url: HttpUrl
m = MyModel(url='http://www.example.com')# the repr() method for a url will display all properties of the urlprint(repr(m.url))# HttpUrl('http://www.example.com', scheme='http', host='www.example.com',# tld='com', host_type='domain', port='80')print(m.url.scheme)# httpprint(m.url.host)# www.example.comprint(m.url.host_type)# domainprint(m.url.port)
from pydantic import BaseModel, ValidationError
from pydantic.color import Color
c = Color('ff00ff')print(c.as_named())#> magentaprint(c.as_hex())#> #f0f
c2 = Color('green')print(c2.as_rgb_tuple())#> (0, 128, 0)print(c2.original())#> greenprint(repr(Color('hsl(180, 100%, 50%)')))#> Color('cyan', rgb=(0, 255, 255))classModel(BaseModel):
color: Color
print(Model(color='purple'))#> color=Color('purple', rgb=(128, 0, 128))try:
Model(color='hello')except ValidationError as e:print(e)"""
1 validation error for Model
color
value is not a valid color: string not recognised as a valid color
(type=value_error.color; reason=string not recognised as a valid color)
"""
from pydantic import BaseModel, SecretStr, SecretBytes
classSimpleModel(BaseModel):
password: SecretStr
password_bytes: SecretBytes
sm = SimpleModel(password='IAmSensitive', password_bytes=b'IAmSensitiveBytes')print(sm.password)# **********print(sm.password_bytes)# **********print(sm.json())# {"password": "**********", "password_bytes": "**********"}# 获取真实数据print(sm.password.get_secret_value())# IAmSensitiveprint(sm.password_bytes.get_secret_value())# b'IAmSensitiveBytes'# If you want the secret to be dumped as plain-text using the json method,# you can use json_encoders in the Config class.classSimpleModelDumpable(BaseModel):
password: SecretStr
password_bytes: SecretBytes
classConfig:# 在调用json方法时会对值进行解析
json_encoders ={
SecretStr:lambda v: v.get_secret_value()if v elseNone,
SecretBytes:lambda v: v.get_secret_value()if v elseNone,}
sm2 = SimpleModelDumpable(password='IAmSensitive', password_bytes=b'IAmSensitiveBytes')print(sm2.password)# **********print(sm2.dict())"""
{
'password': SecretStr('**********'),
'password_bytes': SecretBytes(b'**********'),
}
"""## But the json method willprint(sm2.json())"""
{
"password": "IAmSensitive",
"password_bytes": "IAmSensitiveBytes"
}
"""
12.Json类型
自动将json串转为对象
from typing import List
from pydantic import BaseModel, Json, ValidationError
classSimpleJsonModel(BaseModel):
json_obj: Json
classComplexJsonModel(BaseModel):
json_obj: Json[List[int]]# obj = SimpleJsonModel(json_obj='{"b": 1}')# print(type(obj.json_obj)) # dict# print(obj.json_obj) # {'b': 1}# obj2 = ComplexJsonModel(json_obj='[1, 2, 3]')# print(type(obj2.json_obj)) # list# print(obj2.json_obj) # [1, 2, 3]try:
ComplexJsonModel(json_obj='["a", "b"]')except ValidationError as e:print(e)"""
2 validation errors for ComplexJsonModel
json_obj -> 0
value is not a valid integer (type=type_error.integer)
json_obj -> 1
value is not a valid integer (type=type_error.integer)
"""
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?