簡體   English   中英

在 pydantic.validators.find_validators TypeError: issubclass() arg 1 must be a class

[英]in pydantic.validators.find_validators TypeError: issubclass() arg 1 must be a class

您好,我正在閱讀具有以下格式的 JSON:

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

如您所見,鍵是數字,但不是連續的。

所以我對嵌套的dict有以下BaseModel

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

問題是如何驗證dict中的所有項目都是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]

編輯

驗證前一個的錯誤是:

in pydantic.validators.find_validators TypeError: issubclass() arg 1 must be a class

這可能嗎?

謝謝

您可以更改模型定義以使用自定義根類型(不需要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 。)

(如果您想直接訪問__root__字段中的項目,pydantic 文檔還建議在模型上實現自定義__iter____getitem__方法。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM