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

3 投票
2 回答
2401 浏览
提问于 2025-04-18 06:46

python-eve REST API框架中,我在一个资源里定义了一个列表,这个列表里的每个项目都是字典类型。我不想让这个列表是空的。那么,我该怎么定义这个结构呢?

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

2 个回答

-1

这个功能没有现成的方法可以直接使用。不过,你可以为你的列表定义一个包装类:

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。如果你想的话,可以把模式的定义放在外面,然后作为输入传给构造函数。

另外:你可能想看看 这个链接

2

目前,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 错误信息,可以这样做:

from eve.io.mongo import Validator
from cerberus import errors

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, errors.ERROR_EMPTY_NOT_ALLOWED)

然后你可以这样运行你的 API:

app = Eve(validator=MyValidator)
app.run()

另外,我计划在未来的某个时候将列表和字典添加到 Cerberus 的 empty 规则中。

撰写回答