【问题标题】:How to display list data from SqlAlchemy Query using fastAPI如何使用 fastAPI 显示来自 SqlAlchemy Query 的列表数据
【发布时间】: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


【解决方案1】:

@MatsLindh 提出的这个方案解决了。

那不是正在加载的端点;错误消息抱怨设置了 id 的端点(即 /get/{id} 或类似的东西)。您可能在 /get/all 端点之前定义了该端点,并且由于 all 不是整数,它会引发给定的错误。

这解决了我的问题,因为我在 /get/all 端点之前有另一个端点,名为 /get/{id},这导致了错误。

【讨论】:

    猜你喜欢
    • 2021-07-01
    • 1970-01-01
    • 2017-09-20
    • 2021-07-09
    • 2021-05-16
    • 1970-01-01
    • 2022-12-12
    • 2021-06-20
    • 2013-01-19
    相关资源
    最近更新 更多