我有一个终结点,它返回一个PYDANIC对象.然而,我希望在某些情况下响应代码不是200(例如,如果我的服务不正常).我如何使用FastAPI实现这一点?

class ServiceHealth(BaseModel):
    http_ok: bool = True
    database_ok: bool = False

    def is_everything_ok(self) -> bool:
        return self.http_ok and self.database_ok

@router.get("/health")
def health() -> ServiceHealth:
    return ServiceHealth()

推荐答案

你可以退还Response Directly美元.

例如,您可以使用JSONResponse并手动设置status:

@router.get("/health")
async def health() -> ServiceHealth:
    response = ServiceHealth()
    
    if response.is_everything_ok():
        return JSONResponse(content=response.dict(), status=200)
    return JSONResponse(content=response.dict(), status=500)

此外,您还可以从fastapi导入一个方便的status.py,其中包含所有可用的状态代码:

from fastapi import status

@router.get("/health")
async def health() -> ServiceHealth:
    response = ServiceHealth()
    
    if response.is_everything_ok():
        return JSONResponse(content=response.dict(), status=status.HTTP_200_OK)
    return JSONResponse(content=response.dict(), status=status.HTTP_500_INTERNAL_SERVER_ERROR)

Python相关问答推荐

为什么Pydantic在我申报邮箱时说邮箱丢失

Pandas .类型错误:只能将字符串(而不是int)连接到字符串

Pandas滚动分钟,来自其他列的相应值

单击Python中的复选框后抓取数据

如何让pyparparsing匹配1天或2天,但1天和2天失败?

pandas DataFrame中类型转换混乱

使用LineConnection动画1D数据

如何在BeautifulSoup中链接Find()方法并处理无?

按列分区,按另一列排序

如何使用LangChain和AzureOpenAI在Python中解决AttribeHelp和BadPressMessage错误?

如何在类和classy-fastapi -fastapi- followup中使用FastAPI创建路由

当从Docker的--env-file参数读取Python中的环境变量时,每个\n都会添加一个\'.如何没有额外的?

ODE集成中如何终止solve_ivp的无限运行

梯度下降:简化要素集的运行时间比原始要素集长

从spaCy的句子中提取日期

以逻辑方式获取自己的pyproject.toml依赖项

在pandas/python中计数嵌套类别

重置PD帧中的值

如何检测鼠标/键盘的空闲时间,而不是其他输入设备?

如何找出Pandas 图中的连续空值(NaN)?