这完全取决于您的需求,fastapi 中没有原生实现的健康端点。
但有人告诉我,在开始集成代码之前,我需要设置一个健康端点。
这不一定是一个坏习惯,您可以从列出所有未来的健康检查开始,然后从那里构建您的路线。
评论更新:
但我不知道如何实现。我需要一个配置文件吗?我对此很陌生。
据我了解,您对 python api 非常陌生,因此您应该从关注 official fastapi user guide 开始。你也可以从this关注fastapi first steps。
按原样运行的非常基本的一个文件项目:
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/health")
async def root():
return {"message": "Alive!"}
请记住,以上内容不适用于生产,仅用于测试/学习目的,要制作生产api,您应该遵循官方advanced user guide并实现类似以下内容。
更高级的路由器:
你有 this health lib 的 fastapi 很好。
您可以像这样进行基本检查:
# app.routers.health.py
from fastapi import APIRouter, status, Depends
from fastapi_health import health
from app.internal.health import healthy_condition, sick_condition
router = APIRouter(
tags=["healthcheck"],
responses={404: {"description": "not found"}},
)
@router.get('/health', status_code=status.HTTP_200_OK)
def perform_api_healthcheck(health_endpoint=Depends(health([healthy_condition, sick_condition]))):
return health_endpoint
# app.internal.health.py
def healthy_condition(): # just for testing puposes
return {"database": "online"}
def sick_condition(): # just for testing puposes
return True