简单的数据验证

Posted

技术标签:

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

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

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

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

【问题讨论】:

我对此并不十分熟悉,但我认为您可能想要使用 ORM(请参阅 ***.com/questions/2781682/mongodb-orm-for-python) - 尽管您会失去 NoSQL DB 的灵活性。 谢谢。我知道使用 ORM 的可能性,但在这种情况下,我想直接操作 MongoDB 数据库。 github.com/nicolaiarocci/cerberus。我喜欢妖娆,但现在更喜欢地狱犬。所有规则都可以在人类可读的 yaml 文件中声明,而不需要在 voluptuous 和其他库中调用可调用对象。 docs.python-cerberus.org/en/stable 这个怎么样 【参考方案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 是否支持条件字段验证?

以上是关于简单的数据验证的主要内容,如果未能解决你的问题,请参考以下文章

在 Codeigniter 中填充表单数据和验证数据的更简单方法?

交叉验证iris数据集

交叉验证iris数据集

利用js编写一个简单的html表单验证,验证通过时提交数据(附源码)

对可验证秘密共享的简单介绍

gin-数据绑定+数据验证