当我使用 fastapi 和 pydantic 构建 POST API 时,出现 TypeError: Object of type is not JSON可序列化

ppo*_*ine 8 python pydantic fastapi

我使用 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
Run Code Online (Sandbox Code Playgroud)

我的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!"}
Run Code Online (Sandbox Code Playgroud)

输入数据格式为json:

{
     "user_id": "123",
     "worker_id": "010",
     "worker_name": "Amos",
     "worker_email": "Amos@mail.com",
     "schedulable": true,
     "roles": {"roles_id": ["001"]}
}
Run Code Online (Sandbox Code Playgroud)

当我执行时,我收到 TypeError: Object of type RolesSchema is not JSON Serialized。

如何修复程序使其正常运行?

ale*_*ame 1

尝试使用roles=create.roles.dict()for createquery而不是roles=create.roles