Flask同时验证装饰器的多个字段 [英] Flask validates decorator multiple fields simultaneously

查看:85
本文介绍了Flask同时验证装饰器的多个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用来自flask的sqlalchemy.orm中的@validates装饰器来验证字段,只要所有字段彼此独立,例如:

I have been using the @validates decorator in sqlalchemy.orm from flask to validate fields, and all has gone well as long as all of the fields are independent of one another such as:

@validates('field_one')
def validates_field_one(self, key, value):
   #field one validation

@validates('field_two')
def validates_field_two(self, key, value):
   #field two validation

但是,现在我需要进行一些验证,这需要同时访问field_one和field_two.看起来validates接受了validates装饰器的多个参数,但是,它将仅对每个参数运行一次验证函数,如下所示:

However, now I need to do some validation that will require access to field_one and field_two simultaneously. It looks like validates accepts multiple arguments to the validates decorator, however, it will simply run the validation function once for each argument, as such:

@validates('field_one', 'field_two')
def validates_fields(self, keys, values):
   #field validation

导致工作流程为验证field_one,然后验证field_two.但是,我想同时验证两者(一个简单的例子是断言field_one的值不是field_two的值,其中一个例子是不允许在其中field_one和field_two的图中进行自循环参照节点,并且它在边缘上执行验证).这样做的最好方法是什么?

Results in a work flow of validate field_one and then validate field_two. However, I would like to validate both at the same time(a trivial example of which would be assert that the value of field_one is not the value of field_two, an example of which would be disallowing self-loops in a graph where field_one and field_two refer to nodes and it is performing validation on an edge). How would be the best way to go about doing that?

推荐答案

按照在模型上定义的顺序对字段进行排序.然后检查最后一个字段是否是正在验证的字段.否则,只需返回未选中的值即可.如果验证程序正在验证较早的字段之一,则其中一些字段将尚未设置.

Order the fields in the order they were defined on the model. Then check if the last field is the one being validated. Otherwise just return the value unchecked. If the validator is validating one of the earlier fields, some of them will not be set yet.

@validates('field_one', 'field_two')
def validates_fields(self, key, value):
    if key == 'field_two':
        assert self.field_one != value
    return value

请参见此示例.

这篇关于Flask同时验证装饰器的多个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆