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>
This commit is contained in:
co-authored by
Claude
parent
2b001dde95
commit
8937799973
@@ -0,0 +1 @@
|
||||
"""运维脚本包。"""
|
||||
@@ -0,0 +1,64 @@
|
||||
# -*- 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()
|
||||
@@ -0,0 +1,25 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
数据库初始化脚本
|
||||
=============================================================
|
||||
|
||||
基于 SQLAlchemy 元数据创建全部数据表(等价 flask db upgrade 的建表)。
|
||||
适合从零初始化环境。
|
||||
|
||||
用法:
|
||||
python scripts/init_db.py
|
||||
"""
|
||||
|
||||
|
||||
def main():
|
||||
from src.app import create_app
|
||||
from src.core.database import db
|
||||
|
||||
app = create_app()
|
||||
with app.app_context():
|
||||
db.create_all()
|
||||
print(f"数据库表初始化完成,共 {len(db.metadata.tables)} 张表")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user