fastapi - Fastapi 和 Pydantic 构建 POST API:TypeError: Object of type is not JSON serializable
问题描述
我对 FastAPI 和 Pydantic 有疑问。
我想建立一个post api,程序显示这个:
@router.post('/productRoute', response_model=SuccessCreate, status_code=status.HTTP_201_CREATED)
async def create_product_route(create: CreatePR):
query = ProductRouteModel.insert().values(
user_id=create.user_id,
route_id=create.route_id,
route_name=create.route_name,
head=create.head.dict(),
body=create.body,
route=create.route
)
await database.execute(query)
return {"status": "Successfully Created!"}
这是 Pydantic 类:
class RouteSchema(BaseModel):
id: str
next: Optional[List[str]]
prev: List[str]
class HeadSchema(BaseModel):
b1: str
b2: str
b3: str
class BodySchema(BaseModel):
a1: Optional[str]
a2: Optional[str]
class CreatePR(BaseModel):
user_id: str
route_id: str
route_name: str
head: HeadSchema
body: List[BodySchema]
route: List[RouteSchema]
最后,我要发布的参数格式:
{
user_id: "test1",
route_id: "route_1",
route_name: "route_name",
head: {...},
body: [{...}, {...}, ..., {...}],
route: [{...}, {...}, ..., {...}]
}
当我执行时,我得到 TypeError: Object of type BodySchema is not JSON serializable。
如何将程序修复为正常运行?
解决方案
您的代码似乎没问题。我不会发表强烈的声明,但我认为您的帖子正文是错误的。您能否验证您的JSON
格式是否正确。您可以使用在线 JSON 编辑器进行检查(例如:https ://jsonbeautifier.org/ )。可能的错误可能是使用单引号、缺少/多余的逗号,甚至可能您忘记在键上加上引号。
推荐阅读
- ruby-on-rails - 如何在 RSpec/Capybara 测试中进行配置更改?
- javascript - ramda 中的 Concat 对象(项目 nodejs)
- python - 如何在我的脚本中打开 file.py 时显示进度条
- python-3.x - 如何将函数中的更改字符串插入到 Tkinter 中的标签中?
- javascript - 当我在不同组件的输入框中键入时反应 Mapbox 组件闪烁
- gradle - 远程 Gradle 脚本插件缓存
- raster - 克里金预测函数为每个值返回 NAN。[r]
- rest - OData 是唯一适用于 SSO/MFA 环境的方法吗?
- typo3 - 我可以在没有文件收集的情况下将 Typo3 fs-media-gallery 与 sys_category 一起使用吗?
- react-native - FlatList 滚动到 Footer 组件