我的web应用程序对每个请求都使用Cerberus模式验证(当前版本是1.2)。为此,我用YAML编写模式,在应用程序启动时加载它并进行验证,并使用许多反向引用来优化我的工作,如下面的模式所示。
在测试/运行时中捕获模式错误是非常不幸的。如何在应用程序启动时验证模式本身,而不为每个模式编写虚拟值?
---
_required_string: &required_string
type: string
empty: False
required: True
nullable: False
# Sign in request body
signin:
type: dict
empty: False
nullable: False
schema:
name: *required_string
password: *required_string发布于 2018-10-08 12:12:40
我希望这能回答你的问题,因为我不太确定我是否正确理解了它。这确实感觉有点像一个变通方法,但它也会做你想做的事情。听起来你想在多个地方重用一组需求。我看到的最佳选择是创建一个自定义Validator子类,并添加一个自定义验证器方法来处理共享规则集。根据您提供的示例,下面的代码应该可以工作。
from cerberus import Validator
import yaml
class MyValidator(Validator):
def _validator_required_string(self, field, value):
# Check the type
if type(value) != str:
self._error(field, "Must be of type 'str'")
# Check the length
if len(value) == 0:
self._error(field, "Cannot be blank")
data = {"signin": { "name": "myusername",
"password": "mypassword"}}
schema = '''
signin:
type: dict
empty: False
nullable: False
schema:
name:
validator: required_string
password:
validator: required_string
'''
v = MyValidator(yaml.load(schema))您可以在此处查看Custom Validators文档以了解命名要求。顺便说一句,如果您可以用Python代码而不是YAML来定义您的模式,那么您可以定义一个required_string变量,该变量保存您想要使用的实际规则的字典,然后在更大的模式定义中引用该变量。这将允许您使用实际的规则,而不必定义一个函数来实现这些规则。
https://stackoverflow.com/questions/52598161
复制相似问题