Python3数据验证包Pydantic入门教程

诸神缄默不语-个人技术博文与视频目录

1. pydantic简介

pydantic文档:https://docs.pydantic.dev/latest/

似乎只支持Python 3.8+

pydantic库是用来做数据验证的,就是比如说你现在有一个函数或者类需要传参,用pydantic可以建立一个数据模型,严格限制输入参数的类型,然后你再将这个数据模型实例化,用来作为输入和使用入参的中间件,在这里卡一下数据类型。

Python有自带的入参类型提示功能,可以参考我之前写的博文:Python3的类型提示和typing库:提示入参的类型
但是默认的类型提示就是纯提示,不会强制限制,不像Java那种默认就强制限制。如果我们希望强制限制用户输入的参数属于某些类型,就可以用pydantic库来实现。

2. 例子1

一个简单的示例代码,展示用pydantic库限制模型输入参数为str对象,但实例化时传入了int对象(1),就会导致报错,在报错信息中会给出原因。Python代码为:

from pydantic import BaseModel


class Model(BaseModel):
    x: str


Model(x=1)

报错信息为:

Traceback (most recent call last):
  File "D:\PythonCode\p3_gold\try2.py", line 8, in <module>
    Model(x=1)
  File "D:\allApplications\forPython\anaconda3\envs\venv_name\Lib\site-packages\pydantic\main.py", line 212, in __init__
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
pydantic_core._pydantic_core.ValidationError: 1 validation error for Model
x
  Input should be a valid string [type=string_type, input_value=1, input_type=int]
    For further information visit https://errors.pydantic.dev/2.9/v/string_type

报错信息中很明显地写了,x参数需要传入string类,但实际传入的是int类的1对象,所以raise error。

3. 例子2:一个复杂点的通过数据验证的示例

BaseModel中给出默认值的参数就是可选的。
pydantic库会进行自动转换入参类型的操作,能转就会自动转,比如字符串转换为数字(但是上例中我们会发现不能反过来转),可以把ISO 8601格式表示时间的字符串自动转换成datetime对象。
model_dump()函数可以将数据模型的参数与值转换为字典对象

from datetime import datetime

from pydantic import BaseModel, PositiveInt


class User(BaseModel):
    id: int  
    name: str = 'John Doe'  
    signup_ts: datetime | None  
    tastes: dict[str, PositiveInt]  


external_data = {
    'id': 123,
    'signup_ts': '2019-06-01 12:22',  
    'tastes': {
        'wine': 9,
        b'cheese': 7,  
        'cabbage': '1',  
    },
}

user = User(**external_data)  

print(user.id)  
#> 123
print(user.model_dump())  
"""
{
    'id': 123,
    'name': 'John Doe',
    'signup_ts': datetime.datetime(2019, 6, 1, 12, 22),
    'tastes': {'wine': 9, 'cheese': 7, 'cabbage': 1},
}
"""

4. 例子3:一个未通过数据验证、查出数据类型不符要求的示例

# continuing the above example...

from datetime import datetime
from pydantic import BaseModel, PositiveInt, ValidationError


class User(BaseModel):
    id: int
    name: str = 'John Doe'
    signup_ts: datetime | None
    tastes: dict[str, PositiveInt]


external_data = {'id': 'not an int', 'tastes': {}}  

try:
    User(**external_data)  
except ValidationError as e:
    print(e.errors())
    """
    [
        {
            'type': 'int_parsing',
            'loc': ('id',),
            'msg': 'Input should be a valid integer, unable to parse string as an integer',
            'input': 'not an int',
            'url': 'https://errors.pydantic.dev/2/v/int_parsing',
        },
        {
            'type': 'missing',
            'loc': ('signup_ts',),
            'msg': 'Field required',
            'input': {'id': 'not an int', 'tastes': {}},
            'url': 'https://errors.pydantic.dev/2/v/missing',
        },
    ]
    """
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

诸神缄默不语

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值