【问题标题】:in pydantic.validators.find_validators TypeError: issubclass() arg 1 must be a class在 pydantic.validators.find_validators TypeError: issubclass() arg 1 must be a class
【发布时间】:2022-07-09 16:45:05
【问题描述】:

您好,我正在阅读以下格式的 JSON

{
"1": {"id":1, "type": "a"}
2: {"id":2, "type": "b"}
"3": {"id":3, "type": "c"}
"5": {"id":4, "type": "d"}
}

如您所见,键是数字,但不是连续的

所以我有以下 BaseModel 到嵌套的字典

@validate_arguments
class ObjI(BaseModel):
    id: int
    type: str

问题是我如何验证字典中的所有项目都是 ObjI 而不使用

objIs = json.load(open(path))
assert type(objIs) == dict
    for objI in objIs.values():
        assert type(objI) == dict
        ObjI(**pair)

我试过了

@validate_arguments
class ObjIs(BaseModel):
    ObjIs:  Dict[Union[str, int], ObjI]

编辑

验证之前的错误是

在 pydantic.validators.find_validators 类型错误:issubclass() arg 1 必须是一个类

这可能吗?

谢谢

【问题讨论】:

    标签: python pydantic


    【解决方案1】:

    您可以将模型定义更改为以下内容(不需要 validate_arguments 装饰器):

    from pydantic import BaseModel
    from typing import Dict
    
    class ObjI(BaseModel):
        id: int
        type: str
    
    class ObjIs(BaseModel):
        __root__: dict[int, ObjI]
    

    现在可以使用 JSON 数据初始化模型,例如像这样:

    import json
    with open("/path/to/data") as file:
        data = json.load(file)
    
    objis = ObjIs.parse_obj(data)
    

    如果data 包含无效类型(或缺少字段),prase_obj() 将引发ValidationError。 例如,如果 data 看起来像这样:

    data = {
        "1": {"id": "x", "type": "a"},
    #                ^
    #                wrong type
        2: {"id": 2, "type": "b"},
        "3": {"id": 3, "type": "c"},
        "4": {"id": 4, "type": "d"},
    }
    
    objs = ObjIs.parse_obj(data)
    

    这会导致:

    pydantic.error_wrappers.ValidationError: 1 validation error for ObjIs
    __root__ -> 1 -> id
      value is not a valid integer (type=type_error.integer)
    

    这告诉我们带有键1 的对象的id 的类型无效。

    (您可以像 Python 中的任何其他异常一样捕获和处理 ValidationError。)

    【讨论】:

    • 嗨,保罗,问题是关于嵌套对象,我不想像数组一样设置,因为根键是数据库 ID 并且不是连续的,那么可能吗?
    • @Tlaloc-ES - 抱歉耽搁了,我现在已经更新了解决方案。
    猜你喜欢
    • 1970-01-01
    • 2023-03-12
    • 2020-03-23
    • 2011-01-28
    • 1970-01-01
    • 2021-05-13
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    相关资源
    最近更新 更多