登录
首页 >  文章 >  python教程

Pydantic • 处理验证和清理数据

来源:dev.to

时间:2024-08-17 21:30:55 157浏览 收藏

从现在开始,我们要努力学习啦!今天我给大家带来《Pydantic • 处理验证和清理数据》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!

Pydantic • 处理验证和清理数据

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

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

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

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 • 处理验证和清理数据》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>