gpt4 book ai didi

python - 当我使用fastapi和pydantic构建POST API时,出现TypeError : Object of type is not JSON serializable

转载 作者:行者123 更新时间:2023-12-04 17:22:43 25 4
gpt4 key购买 nike

我使用 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。
如何修复程序使其正常运行?

最佳答案

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

关于python - 当我使用fastapi和pydantic构建POST API时,出现TypeError : Object of type is not JSON serializable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65230997/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com