总结
豆包 AI 助手文章总结

Pydantic • 处理验证和清理数据

WBOY
发布: 2024-08-16 09:06:03
转载
633人浏览过

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 • 处理验证和清理数据的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:dev.to网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
豆包 AI 助手文章总结
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号