baodan/scripts/setup/patch_app.py

72 lines
2.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""修补基础平台 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"
' """Register insurance Blueprint after base platform app is created."""\n'
" import os\n"
" # 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"
" '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"
" # 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
# 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)
# 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,
)
# 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)
print("[patch_app.py] Patched app.py with insurance Blueprint registration and migration.")
if __name__ == "__main__":
patch_app_py()