【问题标题】:TypeError: Object of type 'type' is not JSON serializableTypeError: \'type\' 类型的对象不是 JSON 可序列化的
【发布时间】:2023-01-20 15:20:43
【问题描述】:

该代码在 Postman 中运行良好并提供有效响应但无法生成文档

class Role(str, Enum):
     Internal = "internal"
     External = "external"


class Info(BaseModel):
    id: int
    role: Role

class AppInfo(Info):
    info: str


@app.post("/api/v1/create", status_code=status.HTTP_200_OK)
async def create(info: Info, apikey: Union[str, None] = Header(str)):
    if info:
        alias1 = AppInfo(info="Portal Gun", id=123, role=info.role)
        alias2 = AppInfo(info="Plumbus", id=123, , role=info.role)
        info_dict.append(alias1.dict())
        info_dict.append(alias2.dict())

        
        return {"data": info_dict}
    else:
        
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Please provide the input"
        )

收到错误:

TypeError: Object of type 'type' is not JSON serializable

【问题讨论】:

  • 你在运行什么命令?
  • uvicorn app.main:app --reload 我在 app 文件夹中有一个 main.py
  • 我怀疑 role: Role 行,因为 type 是 Python 中所有类的类型。

标签: python enums header fastapi pydantic


【解决方案1】:

我认为问题可能出在:

apikey: Union[str, None] = Header(str)

在异步函数create()

也许函数或类 Header() 不接受 str 作为输入?

虽然我真的不知道那个函数是做什么的//它来自哪个库。

【讨论】:

  • 我在邮递员中提供标题,它工作正常
  • 您能否提供错误代码的回溯?
猜你喜欢
  • 2021-11-13
  • 1970-01-01
  • 1970-01-01
  • 2021-03-11
  • 2019-11-21
  • 2018-09-22
  • 2019-01-17
  • 2019-12-07
  • 2017-09-05
相关资源
最近更新 更多