FastAPI 响应中的项目列表

List of items in FastAPI response

在我的 Fast API 应用程序中,我有这个 pydantic 模型

class UserInArticleView(BaseModel):
    """What fields will be in nested sent_to_user list."""

    telegram_id: int

    class Config:
        """Enable ORM mode."""

        orm_mode = True

class ArticleBase(BaseModel):
    id: int
    text: str = Field(..., min_length=50, max_length=1024)
    image_url: HttpUrl = Field(..., title="Image URL")
    language_code: str = Field("ru", max_length=3, min_length=2)
    sent_to_user: List[UserInArticleView] = []

    class Config:
        orm_mode = True

响应是

[
  {
    "id": 1,
    "text": "Some text",
    "image_url": "http://test.tt/",
    "language_code": "ru",
    "sent_to_user": [
      {
        "telegram_id": 444444444
      },
      {
        "telegram_id": 111111111
      }
    ]
  }
]

有没有一种方法可以将“sent_to_user”作为值列表作为响应,如下所示? 原因是我需要检查 IN 条件。

"sent_to_user": [
  444444444,
  111111111
]

最终的解决方案是:

@app.get("/articles/{article_id}", tags=["article"])
def read_article(article_id: int, db: Session = Depends(get_db)):
    """Read single article by id."""
    db_article = crud.get_article(db, article_id=article_id)
    if db_article is None:
        raise HTTPException(status_code=404, detail="Article not found")
    list_sent_to_user = [i.telegram_id for i in db_article.sent_to_user]
    print("list", list_sent_to_user)
    return list_sent_to_user

为此,您可以创建一个新的 pydantic 模型来扩展您的 ArticleBase 模型,并将 sent_to_user 的类型重新分配给 intList 并使用它您的回复模板

class ArticleBase(BaseModel):
    id: int
    text: str = Field(..., min_length=50, max_length=1024)
    image_url: HttpUrl = Field(..., title="Image URL")
    language_code: str = Field("ru", max_length=3, min_length=2)
    sent_to_user: List[UserInArticleView] = []

    class Config:
        orm_mode = True


class ArticleResponse(ArticleBase):
    sent_to_user: List[int] = []

然后,您必须格式化您的答案以符合要求的格式:

list_int = [elt['telegram_id'] for elt in result_articles['sent_to_user']]

示例集成:


@router.get('/articles/{article_id}',
    summary="get article"
    status_code=status.HTTP_200_OK,
    response_model=ArticleResponse)
def update_date(article_id:int):
   articles = get_article(article_id)
   articles.sent_to_user = [elt.telegram_id for elt in articles.sent_to_user]

   return articles

该代码还没有经过真正的测试,只是为了提供一个集成所提供代码的想法