"FastAPIError: Invalid args for response field! Hint: check that <class 'typing._UnionGenericAlias'> is a valid pydantic field type"

"FastAPIError: Invalid args for response field! Hint: check that <class 'typing._UnionGenericAlias'> is a valid pydantic field type"

我有以下 Pydantic 架构用于 FastAPI 应用程序。

在下面的模式中,每当我将 ParameterSchema 作为 params 的模式验证器时,它会给我以下错误:

fastapi.exceptions.FastAPIError: Invalid args for response field! Hint: check that <class 'typing._GenericAlias'> is a valid pydantic field type

我不知道发生了什么!

class ParameterSchema(BaseModel):
    expiryDate = Optional[datetime]

    class Config:
        arbitrary_types_allowed = True


class RequestProvisioningEventData(BaseModel):
    some_attribute: List[str]
    other_attribute: Optional[List[str]] = []
    bool_attribute: bool
    params: ParameterSchema

    class Config:
        use_enum_values = True

这是因为 expiryDate 分配了 (=) 一个值

class ParameterSchema(BaseModel):
    expiryDate = Optional[datetime]

它应该使用 type hint (:):

class ParameterSchema(BaseModel):
    expiryDate: Optional[datetime]

注意类型提示使用冒号:,不等于=.