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

问题描述 投票:0回答:3

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

{
    'parents' : {
        'type' : 'list',
        'schema' : {
            'parent' : 'string'
        }
    }
}
python eve
3个回答
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()

PS:我计划在未来的某个时候向 Cerberus 的

empty
规则添加列表和字典。


0
投票

您可以考虑尝试 utype 来验证非空列表

import utype

class MySchema(utype.Schema):
    my_list: list = utype.Field(min_length=1)

good = MySchema(my_list=[1,2])

try:
    bad = MySchema(my_list=[])
except Exception as e:
    print(e)
    """
    ParseError: parse item: ['my_list'] failed: Constraint: <min_length>: 1 violated
    """

也是一个 API 框架 使用 utype 解析参数并构建 RESTful API


-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
。如果您愿意,您可以以某种方式外部化模式的定义并将其添加为构造函数的输入。

另外:您可能想看看这个

© www.soinside.com 2019 - 2024. All rights reserved.