【发布时间】:2021-09-15 00:44:37
【问题描述】:
所以,我一直在尝试使用 fastAPI 学习 Python 全栈 Web 开发。我的大部分网站都能正常运行,但我无法使用 FASTAPI 发送查询列表。
我收到此错误。
{
"detail": [
{
"loc": [
"path",
"id"
],
"msg": "value is not a valid integer",
"type": "type_error.integer"
}
]
}
这是我的 FastAPI 路由器代码。
@router.get("/get/all", response_model=List[ComicViewable])
def list_of_all_comics(db: Session = Depends(get_db)):
comics = comic_func.list_comics(db)
if not comics:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
detail="No Comics have been created.")
return comics
这是返回数据库中所有漫画列表的函数。
def list_comics(db: Session):
return db.query(Comic).all()
还有我的 pydantic 响应类
class ComicViewable(BaseModel):
title: str
description: str
date_created: date
is_ongoing: bool
is_public: bool
class Config:
orm_mode = True
我不知道我在这里做错了什么。我已阅读 FASTAPI 帮助文档,其中他们还使用 List[PydanticClassName] 返回数据库查询列表,但由于某种原因,它对我不起作用。
编辑:
所以,我检查了list_comics() 函数的响应。它确实返回了正确的响应。我通过在 Jinja2 模板中打印 comic.title 对其进行了测试。
{% block content %}
<div class="ui segment">
<div class="two column middle aligned grid">
{% for comic in comics %}
<h2>{{comic.title}}</h2>
{% endfor %}
</div>
</div>
{% endblock %}
所以错误似乎发生在 pydantic 类模型 或 FastAPI 路由器 中。
【问题讨论】:
-
那不是正在加载的端点;错误消息抱怨设置了
id的端点(即/get/{id}或类似的东西)。您可能在/get/all端点之前定义了该端点,并且由于all不是整数,它会引发给定的错误。
标签: python sqlalchemy fastapi pydantic