gpt4 book ai didi

fastapi - 如何为 HTTP 400 错误定义单独的 response_model?

转载 作者:行者123 更新时间:2023-12-04 08:00:08 30 4
gpt4 key购买 nike

我被迫将 response_model 中的所有值设置为可选。

class ConnectOut(BaseModel):
product_id: Optional[str]
expires_at: Optional[datetime]
detail: Optional[ErrorType]
如果我不这样做,下面的 HTTP400 路径会引发验证错误,因为如果出现 400 错误,则不会提供 product_id 和 expires_at。
@router_connect.post("/", status_code=200, response_model=ConnectOut)
async def connect(
body: ConnectIn,
response: Response,
):
if account.is_banned:
response.status_code = status.HTTP_400_BAD_REQUEST
return {"detail": ErrorType.USER_IS_BANNED}
有没有办法为成功定义 response_model 和为 400 错误消息定义 response_model ?
非常感谢,

最佳答案

您可以简单地raise HTTPException而不是为给定的响应模型返回不合适的响应,例如:

from fastapi import HTTPException
...
raise HTTPException(status_code=400, detail="Example bad request.")
编辑:
出于文档目的,您可以执行以下操作以使其正确显示:
@example_router.post(
"/example",
response_model=schemas.Example,
status_code=201,
responses={200: {"model": schemas.Example}, 400: {"model": schemas.HTTPError}},
)
def create_example(...) -> models.Example:
...
raise HTTPException(status_code=400, detail="Example bad request.")
HTTPError架构如下所示:
from pydantic import BaseModel

class HTTPError(BaseModel):
"""
HTTP error schema to be used when an `HTTPException` is thrown.
"""

detail: str

关于fastapi - 如何为 HTTP 400 错误定义单独的 response_model?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66514343/

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