【问题标题】:When I use fastapi and pydantic to build POST API, appear a TypeError: Object of type is not JSON serializable当我使用 fastapi 和 pydantic 构建 POST API 时,出现 TypeError: Object of type is not JSON serializable
【发布时间】:2021-03-21 16:01:33
【问题描述】:

我使用 FastAPi 和 Pydantic 对 POST API 的请求和响应进行建模。

我定义了三个类:

from pydantic import BaseModel, Field
from typing import List, Optional, Dict

class RolesSchema(BaseModel):
    roles_id: List[str]

class HRSchema(BaseModel):
    pk: int
    user_id: str
    worker_id: str
    worker_name: str
    worker_email: str
    schedulable: bool
    roles: RolesSchema
    state: dict

class CreateHR(BaseModel):
    user_id: str
    worker_id: str
    worker_name: str
    worker_email: str
    schedulable: bool
    roles: RolesSchema

还有我的 API 程序:

@router.post("/humanResource", response_model=HRSchema)
async def create_humanResource(create: CreateHR):
query = HumanResourceModel.insert().values(
    user_id=create.user_id, 
    worker_id=create.worker_id, 
    worker_name=create.worker_name,
    worker_email=create.worker_email,
    schedulable=create.schedulable,
    roles=create.roles
)
last_record_id = await database.execute(query)
return {"status": "Successfully Created!"}

输入数据格式为json:

{
     "user_id": "123",
     "worker_id": "010",
     "worker_name": "Amos",
     "worker_email": "Amos@mail.com",
     "schedulable": true,
     "roles": {"roles_id": ["001"]}
}

执行时出现 TypeError: Object of type RolesSchema is not JSON serializable。

如何修复程序正常运行?

【问题讨论】:

    标签: python fastapi pydantic


    【解决方案1】:

    尝试使用roles=create.roles.dict() 创建query 而不是roles=create.roles

    【讨论】:

      【解决方案2】:

      如果有人带着错误信息来到这里。

      就我而言:

      data = MyBaseModel(**data) 
      
      # bad - TypeError: Object of type is not JSON serializable
      json.dumps(data)
      
      # good
      data.json()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-02-24
        • 2013-11-25
        • 2019-05-06
        • 2019-10-09
        • 2021-03-02
        • 2013-07-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多