如何定义模式使列表不允许为空?

2024-03-28 12:33:21 发布

您现在位置:Python中文网/ 问答频道 /正文

python-eve REST API framework中,我在资源中定义了一个列表,列表项的类型是dict。我不希望列表为空。那么,如何定义模式呢?在

{
    'parents' : {
        'type' : 'list',
        'schema' : {
            'parent' : 'string'
        }
    }
}

Tags: restapi类型列表定义schematype模式
2条回答

没有一种内在的方法可以做到这一点。不过,您可以为列表定义一个包装类:

class ListWrapper(list):
    # Constructor
    __init__(self, **kwargs):
        allIsGood = False
        # 'kwargs' is a dict with all your 'argument=value' pairs
        # Check if all arguments are given & set allIsGood
        if not allIsGood:
            raise ValueError("ListWrapper doesn't match schema!")
        else:
            # Call the list's constructor, i.e. the super constructor
            super(ListWrapper, self).__init__()

            # Manipulate 'self' as you please

在需要非空列表的任何地方使用ListWrapper。如果您愿意,您可以将模式的定义外部化,并将其作为输入添加到构造函数中。在

另外:您可能想看看this

当前,empty验证规则仅适用于字符串类型,但您可以将标准验证器子类化,使其能够处理列表:

from eve.io.mongo import Validator

class MyValidator(Validator):
    def _validate_empty(self, empty, field, value):
        # let the standard validation happen
        super(Validator, self)._validate_empty(empty, field, value)
        # add your custom list validation
        if isinstance(value, list) and len(value) == 0 and not empty:
            self._error(field, "list cannot be empty")

或者,如果要提供标准的empty错误消息:

^{pr2}$

然后按如下方式运行API:

^{3}$

PS:我计划将来某个时候将列表和dict添加到Cerberus的empty规则中。在

相关问题 更多 >