Files
DjangoAdmin_Flask_EleVue/scripts/health_check.py
T
DjangoAdmin DevandClaude 8937799973 refactor: P9 运维完善(健康端点/Docker 加固/CI-CD/scripts)
- /health 健康端点(白名单已加,Docker HEALTHCHECK 目标)
- docker-compose 加固:build context 修复、privileged false、flask_user、bridge 网络
- .github/workflows/ci.yml:flake8 + mypy + pytest(含 MySQL/Redis 服务)
- scripts/:health_check.py / init_db.py
- Makefile 更新为 src/ 结构

【验收】全项目 flake8 0;12 passed;/health 200;health_check 脚本运行正常
【注】docker-compose 实际构建验证需 Docker 环境执行

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-07 19:51:51 +08:00

65 lines
1.6 KiB
Python

# -*- coding: utf-8 -*-
"""
健康检查脚本
=============================================================
验证应用可构建、健康端点可访问。
用法:
python scripts/health_check.py [--host 127.0.0.1] [--port 8021]
"""
import os
import sys
import requests
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if ROOT not in sys.path:
sys.path.insert(0, ROOT)
def check_app_build() -> bool:
"""验证应用工厂可构建。"""
try:
from src.wsgi import app # noqa: F401
return True
except Exception as e:
print(f"[FAIL] 应用构建失败: {e}")
return False
def check_health_endpoint(host: str, port: int) -> bool:
"""验证 /health 端点可访问。"""
url = f"http://{host}:{port}/health"
try:
resp = requests.get(url, timeout=5)
ok = resp.status_code == 200 and resp.json().get("code") == 0
print(f"[{'OK' if ok else 'FAIL'}] {url} → {resp.status_code}")
return ok
except Exception as e:
print(f"[FAIL] {url} 访问失败: {e}")
return False
def main():
host = "127.0.0.1"
port = 8021
args = sys.argv[1:]
for i, a in enumerate(args):
if a == "--host" and i + 1 < len(args):
host = args[i + 1]
if a == "--port" and i + 1 < len(args):
port = int(args[i + 1])
build_ok = check_app_build()
if build_ok:
# 端点检查(服务器未启动时优雅降级,不阻塞构建校验)
check_health_endpoint(host, port)
sys.exit(0 if build_ok else 1)
if __name__ == "__main__":
main()