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

2024-06-07 15:32:44 发布

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

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

使用serialize_when_none并将类型保留为不需要的(如建议的here)不会检查字段是否存在。在

有简单的方法吗?在


Tags: 模块数据noneapitrue类型here定义
1条回答
网友
1楼 · 发布于 2024-06-07 15:32:44

猴子修补BaseType似乎是实现这一目标的唯一方法。在

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

相关问题 更多 >

    热门问题