gpt4 book ai didi

python - 使用 Python 示意图在必填字段中允许无

转载 作者:太空宇宙 更新时间:2023-11-04 00:33:34 26 4
gpt4 key购买 nike

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

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

有什么简单的方法吗?

最佳答案

Monkey 修补 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

关于python - 使用 Python 示意图在必填字段中允许无,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45016437/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com