378 lines
13 KiB
Python
378 lines
13 KiB
Python
"""
|
|
表单提交系统 - 主入口
|
|
重构为 Blueprint 架构
|
|
"""
|
|
import os
|
|
import sys
|
|
|
|
# 确保项目根目录在 sys.path 中(适配 MCSManager 守护进程等非标准启动方式)
|
|
_PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
if _PROJECT_DIR not in sys.path:
|
|
sys.path.insert(0, _PROJECT_DIR)
|
|
|
|
import ssl
|
|
import hashlib
|
|
import threading
|
|
import time
|
|
import tempfile
|
|
from datetime import datetime, timedelta
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
|
|
from flask import Flask, request, jsonify, redirect, g
|
|
from flask_cors import CORS
|
|
|
|
from config import (
|
|
BASE_DIR, TEMPLATES_DIR, STATIC_DIR, DATA_DIR,
|
|
CERT_FILE, KEY_FILE, HTTP_PORT,
|
|
)
|
|
from db import DB_PATH, is_sqlite, table_exists, MYSQL_CONFIG, init_mysql_session_vars
|
|
from database import (
|
|
init_database, get_all_users, get_user, save_user,
|
|
get_expired_forms, delete_form,
|
|
cleanup_expired_sessions, get_online_users_count,
|
|
init_monitor_tables, insert_business_metric, insert_api_stat,
|
|
get_db_connection,
|
|
)
|
|
|
|
# ========== Flask 应用 ==========
|
|
|
|
app = Flask(__name__, template_folder=TEMPLATES_DIR, static_folder=STATIC_DIR)
|
|
|
|
CORS(app, resources={
|
|
r"/api/*": {
|
|
"origins": "*",
|
|
"methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
|
|
"allow_headers": ["Content-Type", "Authorization"]
|
|
}
|
|
})
|
|
|
|
# ========== 全局状态 ==========
|
|
|
|
zip_creation_locks = {}
|
|
temp_zip_files = {}
|
|
_active_requests_counter = {'count': 0}
|
|
_active_requests_lock = threading.Lock()
|
|
zip_executor = ThreadPoolExecutor(max_workers=3)
|
|
|
|
|
|
# ========== 初始化数据库 ==========
|
|
|
|
print("应用启动,初始化数据库...")
|
|
|
|
if not os.path.exists(DB_PATH) and is_sqlite():
|
|
os.makedirs(DATA_DIR, exist_ok=True)
|
|
init_database()
|
|
else:
|
|
if is_sqlite():
|
|
print(f"✅ 数据库已存在: {DB_PATH}")
|
|
else:
|
|
print(f"✅ 使用 MySQL 数据库: {MYSQL_CONFIG.get('host', 'localhost')}")
|
|
init_database()
|
|
init_mysql_session_vars()
|
|
try:
|
|
with get_db_connection() as conn:
|
|
if not table_exists(conn, 'sessions'):
|
|
print("🔄 检测到 sessions 表不存在,正在创建...")
|
|
from database import init_database as _init
|
|
_init()
|
|
print("✅ sessions 表创建完成")
|
|
else:
|
|
if is_sqlite():
|
|
print("✅ sessions 表已存在")
|
|
except Exception as e:
|
|
print(f"⚠️ 检查/创建 sessions 表失败: {e}")
|
|
|
|
users = get_all_users()
|
|
if not users or 'admin' not in users:
|
|
save_user('admin', {
|
|
'username': 'admin',
|
|
'password_hash': hashlib.sha256('admin123'.encode('utf-8')).hexdigest(),
|
|
'role': 'admin',
|
|
'created_at': datetime.now().isoformat(),
|
|
'managed_forms': [],
|
|
'managed_presets': []
|
|
})
|
|
print("✅ 创建默认管理员账号: admin / admin123")
|
|
|
|
print(f"✅ 数据库初始化完成,当前用户数量: {len(get_all_users())}")
|
|
|
|
try:
|
|
init_monitor_tables()
|
|
except Exception as e:
|
|
print(f"⚠️ 监控表初始化失败: {e}")
|
|
|
|
# 迁移:为已存在的 forms 表补充 announcement 列(幂等)
|
|
try:
|
|
from database import migrate_announcement_column
|
|
migrate_announcement_column()
|
|
except Exception as e:
|
|
print(f"⚠️ announcement 列迁移失败: {e}")
|
|
|
|
# 迁移:为已存在的 forms 表补充 validation 列(幂等,供提交前校验脚本使用)
|
|
try:
|
|
from database import migrate_validation_column
|
|
migrate_validation_column()
|
|
except Exception as e:
|
|
print(f"⚠️ validation 列迁移失败: {e}")
|
|
|
|
# 迁移:每个表单的 Webhook 通知配置(已有表单默认关闭)
|
|
try:
|
|
from database import migrate_webhook_column
|
|
migrate_webhook_column()
|
|
except Exception as e:
|
|
print(f"⚠️ webhook 列迁移失败: {e}")
|
|
|
|
# 迁移:为已存在的 forms 表补充 collecting 列(幂等,收集中/停止收集开关)
|
|
try:
|
|
from database import migrate_collecting_column
|
|
migrate_collecting_column()
|
|
except Exception as e:
|
|
print(f"⚠️ collecting 列迁移失败: {e}")
|
|
|
|
# 迁移:为已存在的 submissions 表补充 device_token 列(幂等,"加载上次填写"功能)
|
|
try:
|
|
from database import migrate_device_token_column
|
|
migrate_device_token_column()
|
|
except Exception as e:
|
|
print(f"⚠️ device_token 列迁移失败: {e}")
|
|
|
|
# 迁移:为已存在的 forms 表补充 duplicate_policy 列(幂等,重复提交策略/匿名模式功能)
|
|
try:
|
|
from database import migrate_duplicate_policy_column
|
|
migrate_duplicate_policy_column()
|
|
except Exception as e:
|
|
print(f"⚠️ duplicate_policy 列迁移失败: {e}")
|
|
|
|
# 迁移:创建提交历史版本表(幂等,提交历史记录/按版本导出功能)
|
|
try:
|
|
from database import migrate_submission_versions
|
|
migrate_submission_versions()
|
|
except Exception as e:
|
|
print(f"⚠️ submission_versions 表迁移失败: {e}")
|
|
|
|
# 迁移:附件由数据库 BLOB 迁移到磁盘 data/files/(幂等)
|
|
try:
|
|
from database import migrate_files_to_disk
|
|
migrate_files_to_disk()
|
|
except Exception as e:
|
|
print(f"⚠️ 附件磁盘存储迁移失败: {e}")
|
|
|
|
|
|
# ========== 图标生成 ==========
|
|
|
|
from utils.icons import generate_favicons
|
|
generate_favicons()
|
|
|
|
|
|
# ========== 启动清理 ==========
|
|
|
|
def cleanup_orphaned_temp_files():
|
|
"""启动时清理孤立的临时ZIP文件"""
|
|
try:
|
|
temp_dir = tempfile.gettempdir()
|
|
cleaned = 0
|
|
for filename in os.listdir(temp_dir):
|
|
if filename.startswith('form_zip_') and filename.endswith('.zip'):
|
|
filepath = os.path.join(temp_dir, filename)
|
|
try:
|
|
stat = os.stat(filepath)
|
|
file_time = datetime.fromtimestamp(stat.st_ctime)
|
|
age = datetime.now() - file_time
|
|
if age > timedelta(hours=1):
|
|
os.remove(filepath)
|
|
cleaned += 1
|
|
print(f"🗑️ 启动清理: 删除遗留临时文件 {filename} (已存在 {age.total_seconds()/3600:.1f} 小时)")
|
|
except Exception as e:
|
|
print(f"⚠️ 清理 {filename} 失败: {e}")
|
|
if cleaned > 0:
|
|
print(f"✅ 启动清理完成: 删除 {cleaned} 个遗留临时文件")
|
|
else:
|
|
print("✅ 启动检查: 没有发现遗留临时文件")
|
|
except Exception as e:
|
|
print(f"❌ 启动清理失败: {e}")
|
|
|
|
cleanup_orphaned_temp_files()
|
|
|
|
|
|
# ========== 注册 Blueprint ==========
|
|
|
|
from routes.auth_routes import bp as auth_bp
|
|
from routes.pages import bp as pages_bp
|
|
from routes.forms import bp as forms_bp
|
|
from routes.submissions import bp as submissions_bp
|
|
from routes.files import bp as files_bp, init_app_state as files_init
|
|
from routes.presets import bp as presets_bp
|
|
from routes.users import bp as users_bp
|
|
from routes.export import bp as export_bp
|
|
|
|
app.register_blueprint(auth_bp)
|
|
app.register_blueprint(pages_bp)
|
|
app.register_blueprint(forms_bp)
|
|
app.register_blueprint(submissions_bp)
|
|
app.register_blueprint(presets_bp)
|
|
app.register_blueprint(users_bp)
|
|
app.register_blueprint(export_bp)
|
|
app.register_blueprint(files_bp)
|
|
|
|
# 注入全局状态到 files 蓝图
|
|
files_init(zip_creation_locks, temp_zip_files)
|
|
|
|
|
|
# ========== 注册 db_manage 和 monitor 路由 ==========
|
|
|
|
from routes.auth import require_admin
|
|
from db_manage_api import register_db_manage_routes
|
|
from monitor_api import register_monitor_routes, collect_metrics_snapshot
|
|
|
|
register_db_manage_routes(app, require_admin)
|
|
register_monitor_routes(app, require_admin, _active_requests_counter)
|
|
|
|
|
|
# ========== 错误处理 ==========
|
|
|
|
@app.errorhandler(404)
|
|
def handle_404(e):
|
|
if request.path.startswith('/api/'):
|
|
return jsonify(error='接口不存在', code=404), 404
|
|
return redirect('/error?code=404')
|
|
|
|
|
|
@app.errorhandler(500)
|
|
def handle_500(e):
|
|
if request.path.startswith('/api/'):
|
|
return jsonify(error='服务器内部错误', code=500), 500
|
|
return redirect('/error?code=500')
|
|
|
|
|
|
# ========== 定时任务 ==========
|
|
|
|
def cleanup_expired_forms_task():
|
|
"""清理过期的表单和文件(根据 expires_at 判断,未设置过期时间的永不过期)"""
|
|
try:
|
|
now_str = datetime.now().isoformat()
|
|
expired_forms = get_expired_forms(now_str)
|
|
|
|
for form_id in expired_forms:
|
|
print(f"清理过期表单: {form_id}")
|
|
delete_form(form_id)
|
|
|
|
if expired_forms:
|
|
print(f"✅ 清理完成: {len(expired_forms)}个表单")
|
|
else:
|
|
print("✅ 没有过期的表单需要清理")
|
|
except Exception as e:
|
|
print(f"❌ 自动清理任务失败: {str(e)}")
|
|
|
|
|
|
def cleanup_temp_zip_files():
|
|
"""清理超过1小时未下载的临时ZIP文件"""
|
|
try:
|
|
cleaned_count = 0
|
|
cutoff_time = datetime.now() - timedelta(hours=1)
|
|
|
|
expired_ids = []
|
|
for temp_file_id, temp_info in list(temp_zip_files.items()):
|
|
try:
|
|
created_at_str = temp_info.get('created_at', '')
|
|
temp_path = temp_info.get('path', '')
|
|
|
|
if created_at_str:
|
|
file_time = datetime.fromisoformat(created_at_str.replace('Z', '+00:00').replace('+00:00', ''))
|
|
if file_time < cutoff_time:
|
|
if os.path.exists(temp_path):
|
|
try:
|
|
os.remove(temp_path)
|
|
print(f"🗑️ 清理过期临时ZIP文件: {temp_path}")
|
|
except Exception as e:
|
|
print(f"❌ 删除文件失败 {temp_path}: {e}")
|
|
expired_ids.append(temp_file_id)
|
|
cleaned_count += 1
|
|
except Exception as e:
|
|
print(f"检查临时文件 {temp_file_id} 失败: {e}")
|
|
|
|
for temp_file_id in expired_ids:
|
|
temp_zip_files.pop(temp_file_id, None)
|
|
|
|
if cleaned_count > 0:
|
|
print(f"✅ 清理临时ZIP完成: {cleaned_count}个文件")
|
|
except Exception as e:
|
|
print(f"❌ 清理临时ZIP失败: {str(e)}")
|
|
|
|
|
|
from apscheduler.schedulers.background import BackgroundScheduler
|
|
|
|
scheduler = BackgroundScheduler()
|
|
scheduler.add_job(cleanup_expired_forms_task, 'cron', hour=2, minute=0)
|
|
scheduler.add_job(cleanup_temp_zip_files, 'cron', hour='*/1')
|
|
scheduler.add_job(cleanup_expired_sessions, 'cron', hour=3, minute=0)
|
|
scheduler.add_job(
|
|
lambda: collect_metrics_snapshot(_active_requests_counter, get_online_users_count),
|
|
'interval', minutes=1
|
|
)
|
|
scheduler.start()
|
|
print("✅ 自动清理任务已启动 (每天凌晨2点执行)")
|
|
print("✅ 临时ZIP清理任务已启动 (每小时执行)")
|
|
print("✅ 会话清理任务已启动 (每天凌晨3点清理过期会话)")
|
|
print("✅ 系统指标采集任务已启动 (每分钟执行)")
|
|
|
|
|
|
# ========== 监控中间件 ==========
|
|
|
|
@app.before_request
|
|
def monitor_before_request():
|
|
"""请求开始:计数 + 记录开始时间"""
|
|
g.monitor_start_time = time.time()
|
|
g.monitor_request_size = request.content_length or 0
|
|
with _active_requests_lock:
|
|
_active_requests_counter['count'] += 1
|
|
|
|
|
|
@app.after_request
|
|
def monitor_after_request(response):
|
|
"""请求结束:减计数 + 记录API调用统计"""
|
|
try:
|
|
with _active_requests_lock:
|
|
_active_requests_counter['count'] = max(0, _active_requests_counter['count'] - 1)
|
|
|
|
if request.path.startswith('/api/') and not request.path.startswith('/api/monitor/'):
|
|
elapsed_ms = int((time.time() - g.get('monitor_start_time', time.time())) * 1000)
|
|
has_error = response.status_code >= 400
|
|
bytes_in = g.get('monitor_request_size', 0)
|
|
bytes_out = response.content_length or 0
|
|
try:
|
|
insert_api_stat(
|
|
endpoint=request.path,
|
|
method=request.method,
|
|
time_ms=elapsed_ms,
|
|
has_error=has_error,
|
|
bytes_in=bytes_in,
|
|
bytes_out=bytes_out
|
|
)
|
|
except Exception:
|
|
pass
|
|
except Exception:
|
|
pass
|
|
return response
|
|
|
|
|
|
# ========== 主程序入口 ==========
|
|
|
|
if __name__ == '__main__':
|
|
try:
|
|
print("🚀 正在启动 Flask 服务器...")
|
|
|
|
if False:
|
|
print(f"🔐 检测到SSL证书,启用HTTP/HTTPS兼容模式")
|
|
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
|
context.load_cert_chain(str(CERT_FILE), str(KEY_FILE))
|
|
app.run(host='0.0.0.0', port=HTTP_PORT, ssl_context=context, debug=True)
|
|
else:
|
|
print(f"⚠️ 未检测到SSL证书,使用HTTP模式")
|
|
print(f"监听地址: http://0.0.0.0:{HTTP_PORT}")
|
|
app.run(host='0.0.0.0', port=HTTP_PORT, debug=True)
|
|
except Exception as e:
|
|
print(f"❌ 服务器启动失败: {e}")
|
|
import traceback
|
|
traceback.print_exc()
|
|
input("按回车键退出...")
|