【问题标题】:Simple data validation简单的数据验证
【发布时间】:2012-08-27 10:32:00
【问题描述】:

我正在编写一个 python 模块,其中包含一些操作 mongodb 数据库的函数。

如何在将输入数据保存到数据库之前验证传递给该函数的输入数据?

例如,假设模块中的函数之一是createUser(user),它接受python 字典作为参数。该字典包含要保存在数据库中的用户信息。我想创建一个自动验证例程来检查字典结构是否与数据库结构匹配。

【问题讨论】:

标签: python python-module validation


【解决方案1】:

我几天前发布了“pyvaru”(https://github.com/daveoncode/pyvaru),它是一个简单、灵活、不显眼的 Python 3 (3.4+) 数据验证库,基于验证规则的概念。

引用自文档:

给定一个要验证的现有模型,如下面的模型(但它可以 是一个简单的字典或任何数据结构,因为 pyvaru 没有 对数据格式做出任何假设):

class User:
    def __init__(self, first_name: str, last_name: str, date_of_birth: datetime, sex: str):
        self.first_name = first_name
        self.last_name = last_name
        self.date_of_birth = date_of_birth
        self.sex = sex

我们必须通过实现 get_rules() 方法来定义一个验证器 对于我们要验证的每个字段,我们必须提供一个或多个 适当的规则。

from pyvaru import Validator
from pyvaru.rules import TypeRule, FullStringRule, ChoiceRule, PastDateRule

class UserValidator(Validator):
    def get_rules(self) -> list:
        user = self.data # type: User
        return [
            TypeRule(apply_to=user,
                     label='User',
                     valid_type=User,
                     error_message='User must be an instance of user model.',
                     stop_if_invalid=True),
            FullStringRule(user.first_name, 'First name'),
            FullStringRule(user.last_name, 'Last name'),
            ChoiceRule(user.sex, 'Sex', choices=('M', 'F')),
            PastDateRule(user.date_of_birth, 'Date of birth')
        ]

关于如何使用我们的自定义验证器,我们有两种选择:

作为上下文处理器:

with UserValidator(user):
    # do whatever you want with your valid model

在这种情况下,只有当 验证成功,否则 ValidationException(包含 带有相应报告的 validation_result 属性)被提出。

通过调用 validate() 方法(返回 ValidationResult)

validation = UserValidator(user).validate()
if validation.is_successful():
    # do whatever you want with your valid model
else:
    # you can take a proper action and access validation.errors
    # in order to provide a useful message to the application user,
    # write logs or whatever

假设我们有一个如下配置的用户实例:

user = User(first_name=' ',
            last_name=None,
            date_of_birth=datetime(2020, 1, 1),
            sex='unknown')

通过使用之前定义的规则运行验证,我们将获得 带有以下错误的 ValidationResult:

{
    'First name': ['String is empty.'],
    'Last name': ['Not a string.'],
    'Sex': ['Value not found in available choices.'],
    'Date of birth': ['Not a past date.']
}

【讨论】:

  • pyvaru 是否支持条件字段验证?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-18
  • 1970-01-01
  • 2011-06-25
  • 1970-01-01
  • 2022-10-04
  • 2016-05-22
相关资源
最近更新 更多