使用Python原理图在必填字段中不允许

使用Python原理图在必填字段中不允许,python,validation,schema,Python,Validation,Schema,为了验证API中的数据,我使用schematics模块定义了一个模式。我希望确保所有字段都存在并包含有效值。设置required=True不允许值为None 当_none时使用序列化_并将类型保留为非必需(如建议)不会检查该字段是否存在 有简单的方法吗?猴子修补基类型似乎是实现这一点的唯一方法 from schematics.exceptions import ConversionError from schematics.undefined import Undefined from sche

为了验证API中的数据,我使用
schematics
模块定义了一个模式。我希望确保所有字段都存在并包含有效值。设置
required=True
不允许值为
None

当_none时使用
序列化_
并将类型保留为非必需(如建议)不会检查该字段是否存在


有简单的方法吗?

猴子修补
基类型似乎是实现这一点的唯一方法

from schematics.exceptions import ConversionError
from schematics.undefined import Undefined
from schematics.types import BaseType

def check_required(self, value, context):
    if self.required and value is Undefined:
        if self.name is None or context and not context.partial:
            raise ConversionError(self.messages['required'])

BaseType.check_required = check_required

这似乎更像是一个设计问题,而不是库的问题。如果
None
是字段的有效值,那么该字段就不应该是必需的。也许
schematics
不是检查字段存在的合适库,但是由于我使用它进行模型验证,我只是想我也可以实现这个额外的功能。