首页  >  文章  >  后端开发  >  Pydantic • 处理验证和清理数据

Pydantic • 处理验证和清理数据

PHPz
PHPz原创
2024-08-16 18:03:08230浏览

Pydantic • Dealing with validating and sanitizing data

自从我开始编程以来,我主要使用结构化和过程范例,因为我的任务需要更实用和直接的解决方案。在处理数据提取时,我必须转向新的范式才能实现更有组织的代码。

这种必要性的一个例子是在抓取任务期间,当我需要捕获最初是我知道如何处理的类型的特定数据时,但突然间,它要么不存在,要么在捕获过程中以不同的类型出现.

因此,我不得不添加一些 if'stry 和 catch 块来检查数据是 int 还是 string ...后来发现没有捕获到任何内容,None等等。使用字典时,我最终在以下情况下保存了一些无趣的“默认数据”:

data.get(values, 0)

好吧,令人困惑的错误消息肯定必须停止出现。

这就是 Python 的动态性。变量可以随时更改其类型,直到您需要更清楚地了解正在使用的类型为止。然后突然出现一堆信息,现在我正在阅读如何处理数据验证,IDE 帮助我处理类型提示和有趣的 pydantic 库。

现在,在数据操作等任务中,使用新范例,我可以拥有显式声明其类型的对象,以及允许验证这些类型的库。如果出现问题,通过查看更好描述的错误信息来调试会更容易。


派丹提克

所以,这是 Pydantic 文档。有更多疑问,欢迎咨询。

基本上,正如我们所知,我们从以下开始:

pip install pydantic

然后,假设我们希望从包含这些电子邮件的源中捕获电子邮件,其中大多数看起来像这样:“xxxx@xxxx.com”。但有时,它可能是这样的:“xxxx@”或“xxxx”。我们对应该捕获的电子邮件格式毫无疑问,因此我们将使用 Pydantic 验证此电子邮件字符串:

from pydantic import BaseModel, EmailStr

class Consumer(BaseModel):
    email: EmailStr
    account_id: int

consumer = Consumer(email="teste@teste", account_id=12345)

print(consumer)

请注意,我使用了可选的依赖项“email-validator”,通过 pip install pydantic[email] 安装。正如我们所知,当您运行代码时,错误将是无效的电子邮件格式“teste@teste”:

Traceback (most recent call last):
  ...
    consumer = Consumer(email="teste@teste", account_id=12345)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  ...: 1 validation error for Consumer
email
  value is not a valid email address: The part after the @-sign is not valid. It should have a period. [type=value_error, input_value='teste@teste', input_type=str]

使用可选依赖项来验证数据很有趣,就像创建我们自己的验证一样,Pydantic 通过 field_validator 允许这样做。因此,我们知道 account_id 必须为正且大于零。如果不同,Pydantic 警告存在异常(值错误)会很有趣。代码将是:

from pydantic import BaseModel, EmailStr, field_validator

class Consumer(BaseModel):
    email: EmailStr
    account_id: int

    @field_validator("account_id")
    def validate_account_id(cls, value):
        """Custom Field Validation"""
        if value <= 0:
            raise ValueError(f"account_id must be positive: {value}")
        return value

consumer = Consumer(email="teste@teste.com", account_id=0)

print(consumer)
$ python capture_emails.py
Traceback (most recent call last):
...
    consumer = Consumer(email="teste@teste.com", account_id=0)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

...: 1 validation error for Consumer
account_id
  Value error, account_id must be positive: 0 [type=value_error, input_value=0, input_type=int]
    For further information visit https://errors.pydantic.dev/2.8/v/value_error

现在,使用正确的值运行代码:

from pydantic import BaseModel, EmailStr, field_validator

class Consumer(BaseModel):
    email: EmailStr
    account_id: int

    @field_validator("account_id")
    def validate_account_id(cls, value):
        """Custom Field Validation"""
        if value <= 0:
            raise ValueError(f"account_id must be positive: {value}")
        return value

consumer = Consumer(email="teste@teste.com", account_id=12345)

print(consumer)
$ python capture_emails.py
email='teste@teste.com' account_id=12345

对吗?!

我还阅读了一些有关本机“dataclasses”模块的内容,该模块更简单一些,并且与 Pydantic 有一些相似之处。然而,Pydantic 更适合处理需要验证的更复杂的数据模型。 Dataclasses 原生包含在 Python 中,而 Pydantic 还没有——至少现在还没有。

以上是Pydantic • 处理验证和清理数据的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn