Python 如何定义模式以使列表不允许为空?
在“我在资源中定义列表”中,列表项的类型是dict,我不希望列表为空。那么,如何定义模式呢Python 如何定义模式以使列表不允许为空?,python,eve,Python,Eve,在“我在资源中定义列表”中,列表项的类型是dict,我不希望列表为空。那么,如何定义模式呢 { 'parents' : { 'type' : 'list', 'schema' : { 'parent' : 'string' } } } 没有一种内在的方法可以做到这一点。不过,您可以为列表定义包装器类: class ListWrapper(list): # Constructor __init
{
'parents' : {
'type' : 'list',
'schema' : {
'parent' : 'string'
}
}
}
没有一种内在的方法可以做到这一点。不过,您可以为列表定义包装器类:
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
。如果愿意,您可以以某种方式将模式的定义外部化,并将其作为输入添加到构造函数中
另外:您可能想看看当前的
空验证规则仅适用于字符串类型,但您可以对标准验证程序进行子类化,使其能够处理列表:
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")
或者,如果希望提供标准的空错误消息:
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:我计划在将来的某个时候将列表和dict添加到Cerberus的empty
规则中。你的意思是定义一个自定义的验证规则,比如“否”吗?我没有,因为我不想使用外部包。如果使用eve,您可以添加一个验证程序来验证您的字段。感谢您的回复。