简单的数据验证

anu*_*jkk 23 python validation python-module

我正在编写一个python模块,它将包含一些将操作mongodb数据库的函数.

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

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

dav*_*ode 4

几天前我发布了“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
Run Code Online (Sandbox Code Playgroud)

我们必须通过实现 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')
        ]
Run Code Online (Sandbox Code Playgroud)

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

作为上下文处理器:

with UserValidator(user):
    # do whatever you want with your valid model
Run Code Online (Sandbox Code Playgroud)

在这种情况下,仅当验证成功时才会执行 with 内的代码,否则将引发 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
Run Code Online (Sandbox Code Playgroud)

假设我们有一个 User 实例,配置如下:

user = User(first_name=' ',
            last_name=None,
            date_of_birth=datetime(2020, 1, 1),
            sex='unknown')
Run Code Online (Sandbox Code Playgroud)

通过使用之前定义的规则运行验证,我们将获得带有以下错误的 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.']
}
Run Code Online (Sandbox Code Playgroud)