Henry
发布于 2025-10-27 / 10 阅读
0
0

Python - FastAPI - 添加 health 接口模块

背景简介

在 Python FastAPI 项目中添加 health 接口。

前置信息

  1. Python 3.11 
  2. FastAPI 0.115.0

详细信息

文件架构

backend/
  |-- app/ # 应用主目录
  |     |-- main.py
  |     |-- api
  |     |     |-- v1
  |     |     |     |-- health.py
  |-- tests/ # 单元测试目录
  |     |-- test_health.py
  |-- docs/ # API 文档目录
  |-- .gitea/
  |-- ci/
  |-- requirements.txt
  |-- Dockerfile 
  |-- pytest.ini

代码准备

  • app/main.py 代码示例
"""
FastAPI 应用入口
-----------------
该文件仅用于启动应用程序实例。
路由定义、配置加载均在独立模块中实现。
"""

from fastapi import FastAPI
from app.api.v1.health import router as health_router
from app.core.config import settings


def create_app() -> FastAPI:
    """
    创建 FastAPI 应用实例
    Returns:
        app (FastAPI): FastAPI 应用对象
    """
    app = FastAPI(
        title=settings.APP_NAME,
        version=settings.VERSION,
        debug=settings.DEBUG,
        description="标准化 FastAPI 模块化架构。",
    )

    # 注册路由
    app.include_router(health_router, prefix="/api/v1", tags=["Health"])

    return app


app = create_app()
  • 添加 app/api/v1/health.py
"""
健康检查接口模块
-----------------
用于检测 FastAPI 应用运行状态,供监控或负载均衡使用。
符合 Kubernetes、Nginx 等探针规范。
"""

from fastapi import APIRouter, status
from fastapi.responses import JSONResponse

router = APIRouter()


@router.get("/health", summary="健康检查", status_code=status.HTTP_200_OK)
async def health_check():
    """
    健康检查接口

    Returns:
        JSONResponse: 返回应用健康状态与服务元信息。

    Example:
        ```bash
        curl -X GET http://localhost:8000/api/v1/health
        ```

    Response:
        ```json
        {
          "code": 0,
          "message": "FastAPI service is healthy."
        }
        ```
    """
    return JSONResponse(
        status_code=status.HTTP_200_OK,
        content={"code": 0, "message": "FastAPI service is healthy."},
    )
  • 添加 tests/test_health.py
"""
健康检查单元测试
-----------------
使用 pytest + httpx 进行异步测试,符合 FastAPI 官方文档规范。
"""

from httpx import AsyncClient
from app.main import app
import pytest


@pytest.mark.asyncio
async def test_health_check():
    """
    测试健康检查接口返回状态与内容。
    """
    async with AsyncClient(app=app, base_url="http://test") as ac:
        response = await ac.get("/api/v1/health")

    assert response.status_code == 200
    data = response.json()
    assert data["code"] == 0
    assert "healthy" in data["message"]
  • 添加 pytest.ini
# pytest.ini
[pytest]
# 指定测试文件所在目录
testpaths = tests
pythonpath = .

# 识别测试文件和函数的命名规则
python_files = test_*.py
python_classes = Test*
python_functions = test_*

# 启用 asyncio 支持(FastAPI 异步测试必需)
asyncio_mode = auto

# 输出样式
addopts = -v --tb=short --disable-warnings

# 日志级别(可选)
log_cli = true
log_cli_level = INFO

验证服务

  • 在根目录运行测试脚本
pytest
plugins: anyio-4.11.0, asyncio-0.24.0
asyncio: mode=Mode.AUTO, default_loop_scope=None
collected 1 item                                                                                                                                                                          

tests/test_health.py::test_health_check 
-------------------------------------------------------------------------------------- live log call --------------------------------------------------------------------------------------
INFO     httpx:_client.py:1786 HTTP Request: GET http://test/api/v1/health "HTTP/1.1 200 OK"
PASSED                                                                                                                                                                              [100%]

============================================================================== 1 passed, 1 warning in 1.59s ===============================================================================
  • 启动 FastAPI 服务
uvicorn app.main:app --reload
INFO:     Will watch for changes in these directories: ['/home/myserver/pers/pers-website/backend']
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [4049773] using WatchFiles
INFO:     Started server process [4049775]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

查看接口信息

  • 查看接口文档:http://localhost:8000/docs


以上便是本文的全部内容,感谢您的阅读,如遇到任何问题,欢迎在评论区留言讨论。



评论