baodan/scripts/setup/patch_app.py

72 lines
2.9 KiB
Python
Raw Normal View History

2026-07-23 17:40:12 +08:00
"""修补基础平台 app.py注册 insurance Blueprint。
Docker 构建时执行将注册代码注入到 app.py
"""
APP_PY = "/app/api/app.py"
INSURANCE_FUNC = (
"\n# ====== Insurance Blueprint Auto-Register ======\n"
"def _register_insurance(app):\n"
2026-07-23 17:40:12 +08:00
' """Register insurance Blueprint after base platform app is created."""\n'
" import os\n"
2026-07-23 17:40:12 +08:00
" # Load insurance module config into Flask app.config\n"
" for key in ['BAODAN_CHAT_API_KEY', 'BAODAN_WORKFLOW_API_KEY', 'BAODAN_API_URL',\n"
" 'BAODAN_KB_API_KEY', 'WECOM_CORP_ID', 'WECOM_SECRET',\n"
" 'WECOM_TOKEN', 'WECOM_AES_KEY', 'WECOM_WEBHOOK_URL',\n"
2026-07-12 14:17:18 +08:00
" 'MAIL_TYPE', 'MAIL_DEFAULT_SEND_FROM', 'SMTP_SERVER',\n"
" 'SMTP_PORT', 'SMTP_USERNAME', 'SMTP_PASSWORD',\n"
" 'SMTP_USE_TLS', 'SMTP_OPPORTUNISTIC_TLS',\n"
" 'RESEND_API_KEY', 'RESEND_API_URL', 'SENDGRID_API_KEY',\n"
" 'JWT_SECRET', 'JWT_EXPIRE_SECONDS', 'GUEST_MODE']:\n"
" if key in os.environ:\n"
" app.config[key] = os.environ[key]\n"
" try:\n"
" from insurance.routes import register_insurance_routes\n"
" register_insurance_routes(app)\n"
2026-07-23 17:40:12 +08:00
" # Run insurance database migrations on startup\n"
" app.config['MIGRATION_ENABLED'] = True\n"
" from insurance.db import run_migrations\n"
" with app.app_context():\n"
" run_migrations()\n"
" except Exception as e:\n"
" import logging\n"
' logging.warning(f"Insurance module not loaded: {e}")\n'
"# ====== END Insurance ======\n\n"
)
def patch_app_py():
with open(APP_PY, "r") as f:
content = f.read()
if "register_insurance_routes" in content:
print("[patch_app.py] Already patched, skipping.")
return
2026-07-23 17:40:12 +08:00
# 1. Insert _register_insurance function definition before "def is_db_command"
marker = "\ndef is_db_command"
if marker in content:
content = content.replace(marker, "\n" + INSURANCE_FUNC + "def is_db_command", 1)
2026-07-23 17:40:12 +08:00
# 2. db command branch: register after app creation
content = content.replace(
" app = create_migrations_app()\n socketio_app = app",
" app = create_migrations_app()\n _register_insurance(app)\n socketio_app = app",
1,
)
2026-07-23 17:40:12 +08:00
# 3. Normal startup branch: register after flask_app creation
content = content.replace(
" socketio_app, flask_app = create_app()\n app = flask_app",
" socketio_app, flask_app = create_app()\n _register_insurance(flask_app)\n app = flask_app",
1,
)
with open(APP_PY, "w") as f:
f.write(content)
2026-07-23 17:40:12 +08:00
print("[patch_app.py] Patched app.py with insurance Blueprint registration and migration.")
if __name__ == "__main__":
patch_app_py()