Files
upload/database.py
T
zzy 84f8516c37 feat(upload): 分片断点续传 + 前端静态资源去 CDN 化
1) 分片上传(routes/chunked.py)
   - POST /api/upload/init  建会话,校验表单/字段/扩展名/体积
   - POST /api/upload/chunk 单片上传,幂等可重传,http body 直写磁盘
   - GET  /api/upload/status 查询已收分片
   - POST /api/upload/complete 按序合并 + sha256 校验 + 清理分片
   - /api/submit 新增 field fileTokens 挂载已上传文件(零拷贝 os.replace)
   - 过期会话(24h)由定时任务清理

2) 弱网下的样式可靠性
   - Tailwind Play CDN / GSAP 改为本地自托管(static/js/vendor/)
   - vendor 资源 1 年 immutable 缓存,自家 css/js 1 小时
   - CSS link 失败自动带 ?r= 重试一次
   - status 页加关键内联样式兜底,极端情况下仍可读

3) 大文件落盘沿用流式写入(无 400MB 内存峰值)
2026-11-13 12:06:32 +08:00

2244 lines
86 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.
"""
数据库模型 - 表单提交系统
文件使用BLOB存储在数据库中
通过 db.py 统一管理数据库连接,支持 SQLite / MySQL 切换
"""
import os
import json
from datetime import datetime, timedelta
from contextlib import contextmanager
import io
from db import get_db_connection, DB_PATH, is_sqlite, is_mysql
from config import DATA_DIR
from utils.webhooks import normalize_webhook
# 附件磁盘存储根目录:data/files/<form_id>/<file_id>.bin
FILES_DIR = os.path.join(os.fspath(DATA_DIR), 'files')
def _disk_path(rel_path):
"""相对路径 → 磁盘绝对路径(相对路径统一使用正斜杠,跨平台可迁移)"""
return os.path.join(FILES_DIR, *rel_path.split('/'))
def _read_file_bytes(row):
"""按 file_path 从磁盘读取文件内容;旧记录(迁移前的 BLOB)回退 file_data 字段。"""
keys = row.keys()
rel = row['file_path'] if 'file_path' in keys else None
if rel:
with open(_disk_path(rel), 'rb') as f:
return f.read()
return row['file_data']
def _unlink_unreferenced(cursor, form_id, rel_path):
"""删除磁盘文件,但仅当 files 与 version_files 两表均无记录引用该路径时。
归档表与当前表可能先后引用同一路径,引用计数避免误删仍被历史版本引用的文件。"""
if not rel_path:
return
cursor.execute('SELECT 1 FROM files WHERE form_id = ? AND file_path = ? LIMIT 1', (form_id, rel_path))
if cursor.fetchone():
return
cursor.execute('SELECT 1 FROM version_files WHERE form_id = ? AND file_path = ? LIMIT 1', (form_id, rel_path))
if cursor.fetchone():
return
try:
os.remove(_disk_path(rel_path))
except OSError:
pass
def init_database():
"""初始化数据库表结构"""
with get_db_connection() as conn:
cursor = conn.cursor()
# 用户表
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
username TEXT PRIMARY KEY,
password_hash TEXT NOT NULL,
role TEXT DEFAULT 'user',
created_at TEXT NOT NULL,
managed_forms TEXT DEFAULT '[]',
managed_presets TEXT DEFAULT '[]'
)
''')
# 表单配置表
cursor.execute('''
CREATE TABLE IF NOT EXISTS forms (
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
collect_type TEXT DEFAULT 'info',
max_size INTEGER DEFAULT 10485760,
allowed_exts TEXT DEFAULT '[]',
fields TEXT NOT NULL,
created_at TEXT NOT NULL,
expires_at TEXT,
creator_ip TEXT,
file_field_count INTEGER DEFAULT 0,
creator TEXT,
preset_id TEXT,
preset_name TEXT,
show_progress INTEGER DEFAULT 1,
verify_digits INTEGER DEFAULT 2,
overwrite_verify TEXT,
announcement TEXT,
validation TEXT,
collecting INTEGER DEFAULT 1,
duplicate_policy TEXT DEFAULT 'overwrite',
webhook TEXT
)
''')
# 表单公告附件表(BLOB存储,按表单划分,独立于提交文件)
cursor.execute('''
CREATE TABLE IF NOT EXISTS form_announcement_files (
id INTEGER PRIMARY KEY AUTOINCREMENT,
form_id TEXT NOT NULL,
filename TEXT NOT NULL,
original_name TEXT,
file_size INTEGER,
mime_type TEXT,
file_data BLOB NOT NULL,
uploaded_at TEXT NOT NULL,
FOREIGN KEY (form_id) REFERENCES forms(id) ON DELETE CASCADE
)
''')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_announcement_files_form ON form_announcement_files(form_id)')
# 预设表
cursor.execute('''
CREATE TABLE IF NOT EXISTS presets (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
original_filename TEXT,
created_at TEXT NOT NULL,
created_by TEXT,
is_global INTEGER DEFAULT 0,
usage_count INTEGER DEFAULT 0,
last_used TEXT,
config TEXT NOT NULL,
students TEXT NOT NULL
)
''')
# 提交记录表
cursor.execute('''
CREATE TABLE IF NOT EXISTS submissions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
form_id TEXT NOT NULL,
student_id TEXT NOT NULL,
student_name TEXT NOT NULL,
tail TEXT NOT NULL,
submitted_at TEXT NOT NULL,
is_overwrite INTEGER DEFAULT 0,
ip_address TEXT,
data TEXT DEFAULT '{}',
device_token TEXT,
FOREIGN KEY (form_id) REFERENCES forms(id) ON DELETE CASCADE
)
''')
# 文件存储表 (BLOB存储)
cursor.execute('''
CREATE TABLE IF NOT EXISTS files (
id INTEGER PRIMARY KEY AUTOINCREMENT,
form_id TEXT NOT NULL,
submission_id INTEGER,
filename TEXT NOT NULL,
original_name TEXT,
file_size INTEGER,
mime_type TEXT,
file_data BLOB NOT NULL,
uploaded_at TEXT NOT NULL,
field_name TEXT,
FOREIGN KEY (form_id) REFERENCES forms(id) ON DELETE CASCADE,
FOREIGN KEY (submission_id) REFERENCES submissions(id) ON DELETE CASCADE
)
''')
# 提交历史记录表
cursor.execute('''
CREATE TABLE IF NOT EXISTS submission_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
form_id TEXT NOT NULL,
student_id TEXT NOT NULL,
submission_time TEXT NOT NULL,
submission_type TEXT,
ip_address TEXT,
FOREIGN KEY (form_id) REFERENCES forms(id) ON DELETE CASCADE
)
''')
# 提交历史版本表:每次提交(含覆盖)归档一份内容快照
cursor.execute('''
CREATE TABLE IF NOT EXISTS submission_versions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
form_id TEXT NOT NULL,
student_id TEXT NOT NULL,
student_name TEXT,
tail TEXT,
data TEXT DEFAULT '{}',
is_overwrite INTEGER DEFAULT 0,
ip_address TEXT,
file_ids TEXT DEFAULT '[]',
submitted_at TEXT NOT NULL,
FOREIGN KEY (form_id) REFERENCES forms(id) ON DELETE CASCADE
)
''')
# 版本附件归档表:被覆盖替换的旧文件移动至此,随版本保留/删除
cursor.execute('''
CREATE TABLE IF NOT EXISTS version_files (
id INTEGER PRIMARY KEY AUTOINCREMENT,
version_id INTEGER NOT NULL,
form_id TEXT NOT NULL,
original_file_id INTEGER,
filename TEXT NOT NULL,
original_name TEXT,
file_size INTEGER,
mime_type TEXT,
file_data BLOB NOT NULL,
field_name TEXT,
archived_at TEXT NOT NULL,
FOREIGN KEY (version_id) REFERENCES submission_versions(id) ON DELETE CASCADE,
FOREIGN KEY (form_id) REFERENCES forms(id) ON DELETE CASCADE
)
''')
# 会话管理表(新增)
cursor.execute('''
CREATE TABLE IF NOT EXISTS sessions (
session_id TEXT PRIMARY KEY,
username TEXT NOT NULL,
role TEXT NOT NULL,
data TEXT DEFAULT '{}',
created_at TEXT NOT NULL,
expires_at TEXT NOT NULL,
last_access_at TEXT NOT NULL,
ip_address TEXT,
user_agent TEXT,
FOREIGN KEY (username) REFERENCES users(username) ON DELETE CASCADE
)
''')
# 创建会话相关索引
cursor.execute('CREATE INDEX IF NOT EXISTS idx_sessions_username ON sessions(username)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_sessions_expires ON sessions(expires_at)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_sessions_last_access ON sessions(last_access_at)')
# 创建索引
cursor.execute('CREATE INDEX IF NOT EXISTS idx_submissions_form ON submissions(form_id)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_submissions_student ON submissions(form_id, student_id)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_files_form ON files(form_id)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_files_submission ON files(submission_id)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_history_form ON submission_history(form_id)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_versions_form_student ON submission_versions(form_id, student_id)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_version_files_version ON version_files(version_id)')
conn.commit()
print("✅ 数据库初始化完成")
def migrate_announcement_column():
"""迁移:为已存在的 forms 表补充 announcement 列 + 创建公告附件表(幂等)"""
from db import get_table_columns, table_exists
with get_db_connection() as conn:
cursor = conn.cursor()
# 1. 确保 forms 表有 announcement 列
cols = get_table_columns(conn, 'forms')
names = [c['name'] for c in cols]
if 'announcement' not in names:
cursor.execute('ALTER TABLE forms ADD COLUMN announcement TEXT')
print("✅ 已为 forms 表添加 announcement 列")
# 2. 确保公告附件表存在
if not table_exists(conn, 'form_announcement_files'):
cursor.execute('''
CREATE TABLE IF NOT EXISTS form_announcement_files (
id INTEGER PRIMARY KEY AUTOINCREMENT,
form_id TEXT NOT NULL,
filename TEXT NOT NULL,
original_name TEXT,
file_size INTEGER,
mime_type TEXT,
file_data BLOB NOT NULL,
uploaded_at TEXT NOT NULL,
FOREIGN KEY (form_id) REFERENCES forms(id) ON DELETE CASCADE
)
''')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_announcement_files_form ON form_announcement_files(form_id)')
print("✅ 已创建 form_announcement_files 表")
def migrate_validation_column():
"""迁移:为已存在的 forms 表补充 validation 列(幂等)"""
from db import get_table_columns
with get_db_connection() as conn:
cursor = conn.cursor()
cols = get_table_columns(conn, 'forms')
names = [c['name'] for c in cols]
if 'validation' not in names:
cursor.execute('ALTER TABLE forms ADD COLUMN validation TEXT')
print("✅ 已为 forms 表添加 validation 列")
conn.commit()
else:
print("✅ validation 列已存在")
def migrate_webhook_column():
"""Add nullable per-form webhook config; existing forms remain disabled."""
from db import get_table_columns
with get_db_connection() as conn:
if 'webhook' not in [col['name'] for col in get_table_columns(conn, 'forms')]:
conn.cursor().execute('ALTER TABLE forms ADD COLUMN webhook TEXT')
conn.commit()
print("✅ 已为 forms 表添加 webhook 列")
def migrate_collecting_column():
"""迁移:为已存在的 forms 表补充 collecting 列(默认 1 = 收集中,幂等)"""
from db import get_table_columns
with get_db_connection() as conn:
cursor = conn.cursor()
cols = get_table_columns(conn, 'forms')
names = [c['name'] for c in cols]
if 'collecting' not in names:
cursor.execute('ALTER TABLE forms ADD COLUMN collecting INTEGER DEFAULT 1')
print("✅ 已为 forms 表添加 collecting 列")
conn.commit()
else:
print("✅ collecting 列已存在")
def migrate_files_to_disk():
"""迁移:附件由数据库 BLOB 改为磁盘存储(幂等)。
- 为 files / version_files 补充 file_path 列
- 将仍存于 BLOB 的旧记录落盘到 data/files/<form_id>/,BLOB 字段清空
- 新上传直接写磁盘,避免大 BLOB 长时间占用数据库写锁(多用户并发上传不再互相等待)"""
from db import get_table_columns
os.makedirs(FILES_DIR, exist_ok=True)
with get_db_connection() as conn:
cursor = conn.cursor()
for table in ('files', 'version_files'):
cols = [c['name'] for c in get_table_columns(conn, table)]
if 'file_path' not in cols:
cursor.execute(f'ALTER TABLE {table} ADD COLUMN file_path TEXT')
print(f"✅ 已为 {table} 表添加 file_path 列")
migrated = 0
for table in ('files', 'version_files'):
cursor.execute(f"""
SELECT * FROM {table}
WHERE file_data IS NOT NULL AND (file_path IS NULL OR file_path = '')
""")
for row in cursor.fetchall():
blob = row['file_data']
if not blob:
continue
rel = f"{row['form_id']}/{table}_{row['id']}.bin"
abs_path = _disk_path(rel)
os.makedirs(os.path.dirname(abs_path), exist_ok=True)
with open(abs_path, 'wb') as f:
f.write(blob)
# NOT NULL 约束保留,清空为 0 字节占位;读取以 file_path 为准
cursor.execute(f'UPDATE {table} SET file_path = ?, file_data = ? WHERE id = ?',
(rel, b'', row['id']))
migrated += 1
print(f"✅ 附件磁盘存储迁移完成,落盘 {migrated} 条旧记录" if migrated
else "✅ 附件磁盘存储检查完成,无待迁移记录")
def migrate_duplicate_policy_column():
"""迁移:为已存在的 forms 表补充 duplicate_policy 列(幂等)
重复提交策略:overwrite=同身份覆盖提交(默认,历史行为);once=禁止重复提交。"""
from db import get_table_columns
with get_db_connection() as conn:
cursor = conn.cursor()
cols = get_table_columns(conn, 'forms')
names = [c['name'] for c in cols]
if 'duplicate_policy' not in names:
cursor.execute("ALTER TABLE forms ADD COLUMN duplicate_policy TEXT DEFAULT 'overwrite'")
conn.commit()
print("✅ 已为 forms 表添加 duplicate_policy 列")
else:
print("✅ duplicate_policy 列已存在")
def migrate_device_token_column():
"""迁移:为已存在的 submissions 表补充 device_token 列(幂等)
用于"加载上次填写"功能:客户端提交时随表单上送随机设备令牌,服务端据此召回该设备最近的提交。"""
from db import get_table_columns
with get_db_connection() as conn:
cursor = conn.cursor()
cols = get_table_columns(conn, 'submissions')
names = [c['name'] for c in cols]
if 'device_token' not in names:
cursor.execute('ALTER TABLE submissions ADD COLUMN device_token TEXT')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_submissions_device ON submissions(device_token, form_id)')
conn.commit()
print("✅ 已为 submissions 表添加 device_token 列")
else:
print("✅ device_token 列已存在")
def migrate_submission_versions():
"""迁移:为已存在的库创建提交历史版本表(幂等)
submission_versions 存每次提交的内容快照;version_files 存被覆盖替换的旧文件。"""
from db import table_exists
with get_db_connection() as conn:
cursor = conn.cursor()
if not table_exists(conn, 'submission_versions'):
cursor.execute('''
CREATE TABLE submission_versions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
form_id TEXT NOT NULL,
student_id TEXT NOT NULL,
student_name TEXT,
tail TEXT,
data TEXT DEFAULT '{}',
is_overwrite INTEGER DEFAULT 0,
ip_address TEXT,
file_ids TEXT DEFAULT '[]',
submitted_at TEXT NOT NULL,
FOREIGN KEY (form_id) REFERENCES forms(id) ON DELETE CASCADE
)
''')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_versions_form_student ON submission_versions(form_id, student_id)')
print("✅ 已创建 submission_versions 表")
else:
print("✅ submission_versions 表已存在")
if not table_exists(conn, 'version_files'):
cursor.execute('''
CREATE TABLE version_files (
id INTEGER PRIMARY KEY AUTOINCREMENT,
version_id INTEGER NOT NULL,
form_id TEXT NOT NULL,
original_file_id INTEGER,
filename TEXT NOT NULL,
original_name TEXT,
file_size INTEGER,
mime_type TEXT,
file_data BLOB NOT NULL,
field_name TEXT,
archived_at TEXT NOT NULL,
FOREIGN KEY (version_id) REFERENCES submission_versions(id) ON DELETE CASCADE,
FOREIGN KEY (form_id) REFERENCES forms(id) ON DELETE CASCADE
)
''')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_version_files_version ON version_files(version_id)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_version_files_original ON version_files(original_file_id)')
print("✅ 已创建 version_files 表")
else:
print("✅ version_files 表已存在")
# ========== 用户相关操作 ==========
def get_all_users():
"""获取所有用户"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('SELECT * FROM users')
rows = cursor.fetchall()
users = {}
for row in rows:
users[row['username']] = {
'username': row['username'],
'password_hash': row['password_hash'],
'role': row['role'],
'created_at': row['created_at'],
'managed_forms': json.loads(row['managed_forms']),
'managed_presets': json.loads(row['managed_presets'])
}
return users
def get_user(username):
"""获取单个用户"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('SELECT * FROM users WHERE username = ?', (username,))
row = cursor.fetchone()
if row:
return {
'username': row['username'],
'password_hash': row['password_hash'],
'role': row['role'],
'created_at': row['created_at'],
'managed_forms': json.loads(row['managed_forms']),
'managed_presets': json.loads(row['managed_presets'])
}
return None
def save_user(username, user_data):
"""保存用户"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
INSERT OR REPLACE INTO users (username, password_hash, role, created_at, managed_forms, managed_presets)
VALUES (?, ?, ?, ?, ?, ?)
''', (
username,
user_data['password_hash'],
user_data.get('role', 'user'),
user_data.get('created_at', datetime.now().isoformat()),
json.dumps(user_data.get('managed_forms', [])),
json.dumps(user_data.get('managed_presets', []))
))
def delete_user(username):
"""删除用户"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('DELETE FROM users WHERE username = ?', (username,))
def update_user_managed_forms(username, form_ids):
"""更新用户管理的表单"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('UPDATE users SET managed_forms = ? WHERE username = ?',
(json.dumps(form_ids), username))
# ========== 表单相关操作 ==========
def get_all_forms():
"""获取所有表单"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('SELECT * FROM forms ORDER BY created_at DESC')
rows = cursor.fetchall()
forms = []
for row in rows:
forms.append(_row_to_form_config(row))
return forms
def get_form(form_id):
"""获取单个表单配置"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('SELECT * FROM forms WHERE id = ?', (form_id,))
row = cursor.fetchone()
if row:
return _row_to_form_config(row)
return None
def save_form(form_config):
"""保存表单配置"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
INSERT OR REPLACE INTO forms
(id, title, collect_type, max_size, allowed_exts, fields, created_at, expires_at,
creator_ip, file_field_count, creator, preset_id, preset_name, show_progress,
verify_digits, overwrite_verify, announcement, validation, collecting, duplicate_policy, webhook)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
form_config['id'],
form_config.get('title', '未命名表单'),
form_config.get('collectType', 'info'),
form_config.get('maxSize', 10 * 1024 * 1024),
json.dumps(form_config.get('allowedExts', [])),
json.dumps(form_config.get('fields', [])),
form_config.get('createdAt', datetime.now().isoformat()),
form_config.get('expiresAt'),
form_config.get('creatorIP'),
form_config.get('fileFieldCount', 0),
form_config.get('creator'),
form_config.get('presetId'),
form_config.get('presetName'),
1 if form_config.get('showProgress', True) else 0,
form_config.get('verifyDigits', 2),
json.dumps(form_config.get('overwriteVerify')) if form_config.get('overwriteVerify') else None,
json.dumps(form_config.get('announcement')) if form_config.get('announcement') else None,
json.dumps(form_config.get('validation')) if form_config.get('validation') else None,
1 if form_config.get('collecting', True) else 0,
'once' if form_config.get('duplicatePolicy') == 'once' else 'overwrite',
json.dumps(normalize_webhook(form_config.get('webhook')))
))
def set_form_collecting(form_id, collecting):
"""开关表单收集状态:collecting=True 收集中 / False 已停止收集(直接 UPDATE,保留其它字段)"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('UPDATE forms SET collecting = ? WHERE id = ?',
(1 if collecting else 0, form_id))
return cursor.rowcount > 0
def delete_form(form_id):
"""删除表单(强制清理所有关联数据,不依赖外键级联)"""
with get_db_connection() as conn:
cursor = conn.cursor()
# 1. 先删除该表单的所有文件(释放BLOB存储空间)
cursor.execute('DELETE FROM files WHERE form_id = ?', (form_id,))
files_deleted = cursor.rowcount
# 1.1 删除该表单的所有公告附件
cursor.execute('DELETE FROM form_announcement_files WHERE form_id = ?', (form_id,))
announcement_files_deleted = cursor.rowcount
# 2. 删除提交历史记录
cursor.execute('DELETE FROM submission_history WHERE form_id = ?', (form_id,))
history_deleted = cursor.rowcount
# 3. 删除提交记录
cursor.execute('DELETE FROM submissions WHERE form_id = ?', (form_id,))
submissions_deleted = cursor.rowcount
# 4. 最后删除表单本身
cursor.execute('DELETE FROM forms WHERE id = ?', (form_id,))
form_deleted = cursor.rowcount
print(f"🗑️ 删除表单 {form_id}: {files_deleted}个文件, {submissions_deleted}条提交, {history_deleted}条历史")
return form_deleted > 0
def _row_to_form_config(row):
"""将数据库行转换为表单配置字典"""
return {
'id': row['id'],
'title': row['title'],
'collectType': row['collect_type'],
'maxSize': row['max_size'],
'allowedExts': json.loads(row['allowed_exts']),
'fields': json.loads(row['fields']),
'createdAt': row['created_at'],
'expiresAt': row['expires_at'],
'creatorIP': row['creator_ip'],
'fileFieldCount': row['file_field_count'],
'creator': row['creator'],
'presetId': row['preset_id'],
'presetName': row['preset_name'],
'showProgress': bool(row['show_progress']),
'verifyDigits': row['verify_digits'],
'overwriteVerify': json.loads(row['overwrite_verify']) if row['overwrite_verify'] else None,
'announcement': (json.loads(row['announcement'])
if _row_has_col(row, 'announcement') and row['announcement'] else None),
'validation': (json.loads(row['validation'])
if _row_has_col(row, 'validation') and row['validation'] else None),
'collecting': bool(row['collecting']) if _row_has_col(row, 'collecting') else True,
'duplicatePolicy': (row['duplicate_policy'] if _row_has_col(row, 'duplicate_policy')
and row['duplicate_policy'] else 'overwrite'),
'webhook': normalize_webhook(json.loads(row['webhook']) if _row_has_col(row, 'webhook') and row['webhook'] else None)
}
def _row_has_col(row, col_name):
"""检查 sqlite3.Row / dict 行是否包含指定列(兼容迁移未执行时的缺失列)"""
try:
keys = row.keys()
return col_name in keys
except Exception:
try:
return col_name in row
except Exception:
return True
# ========== 预设相关操作 ==========
def get_all_presets():
"""获取所有预设"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('SELECT * FROM presets ORDER BY created_at DESC')
rows = cursor.fetchall()
presets = {}
for row in rows:
preset_id = row['id']
presets[preset_id] = {
'id': preset_id,
'name': row['name'],
'originalFilename': row['original_filename'],
'createdAt': row['created_at'],
'createdBy': row['created_by'],
'isGlobal': bool(row['is_global']),
'usageCount': row['usage_count'],
'lastUsed': row['last_used'],
'config': json.loads(row['config']),
'students': json.loads(row['students'])
}
return presets
def get_preset(preset_id):
"""获取单个预设"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('SELECT * FROM presets WHERE id = ?', (preset_id,))
row = cursor.fetchone()
if row:
return {
'id': row['id'],
'name': row['name'],
'originalFilename': row['original_filename'],
'createdAt': row['created_at'],
'createdBy': row['created_by'],
'isGlobal': bool(row['is_global']),
'usageCount': row['usage_count'],
'lastUsed': row['last_used'],
'config': json.loads(row['config']),
'students': json.loads(row['students'])
}
return None
def save_preset(preset_data):
"""保存预设"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
INSERT OR REPLACE INTO presets
(id, name, original_filename, created_at, created_by, is_global, usage_count,
last_used, config, students)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
preset_data['id'],
preset_data.get('name', '未命名预设'),
preset_data.get('originalFilename'),
preset_data.get('createdAt', datetime.now().isoformat()),
preset_data.get('createdBy'),
1 if preset_data.get('isGlobal') else 0,
preset_data.get('usageCount', 0),
preset_data.get('lastUsed'),
json.dumps(preset_data.get('config', {})),
json.dumps(preset_data.get('students', []))
))
def delete_preset(preset_id):
"""删除预设"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('DELETE FROM presets WHERE id = ?', (preset_id,))
def update_preset_usage(preset_id):
"""更新预设使用次数"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
UPDATE presets
SET usage_count = usage_count + 1, last_used = ?
WHERE id = ?
''', (datetime.now().isoformat(), preset_id))
# ========== 提交记录相关操作 ==========
def get_submission(form_id, student_id):
"""获取提交记录"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT * FROM submissions
WHERE form_id = ? AND student_id = ?
''', (form_id, student_id))
row = cursor.fetchone()
if row:
return {
'id': row['id'],
'form_id': row['form_id'],
'student_id': row['student_id'],
'student_name': row['student_name'],
'tail': row['tail'],
'submitted_at': row['submitted_at'],
'is_overwrite': bool(row['is_overwrite']),
'ip_address': row['ip_address'],
'data': json.loads(row['data']) if row['data'] else {}
}
return None
def get_form_submissions(form_id):
"""获取表单的所有提交记录"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('SELECT * FROM submissions WHERE form_id = ?', (form_id,))
rows = cursor.fetchall()
submissions = []
for row in rows:
submissions.append({
'id': row['id'],
'form_id': row['form_id'],
'student_id': row['student_id'],
'student_name': row['student_name'],
'tail': row['tail'],
'submitted_at': row['submitted_at'],
'is_overwrite': bool(row['is_overwrite']),
'ip_address': row['ip_address'],
'data': json.loads(row['data']) if row['data'] else {}
})
return submissions
def save_submission(form_id, student_id, student_name, tail, is_overwrite=False, ip_address=None, data=None, device_token=None):
"""保存提交记录"""
with get_db_connection() as conn:
cursor = conn.cursor()
# 检查是否已存在
cursor.execute('SELECT id FROM submissions WHERE form_id = ? AND student_id = ?',
(form_id, student_id))
existing = cursor.fetchone()
if existing:
# 更新现有记录
cursor.execute('''
UPDATE submissions
SET student_name = ?, tail = ?, submitted_at = ?, is_overwrite = ?,
ip_address = ?, data = ?, device_token = ?
WHERE form_id = ? AND student_id = ?
''', (student_name, tail, datetime.now().isoformat(), 1 if is_overwrite else 0,
ip_address, json.dumps(data or {}), device_token, form_id, student_id))
return existing['id']
else:
# 插入新记录
cursor.execute('''
INSERT INTO submissions
(form_id, student_id, student_name, tail, submitted_at, is_overwrite, ip_address, data, device_token)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (form_id, student_id, student_name, tail, datetime.now().isoformat(),
1 if is_overwrite else 0, ip_address, json.dumps(data or {}), device_token))
return cursor.lastrowid
def find_submission_id(form_id, student_id):
"""该表单下此身份(学号全号/匿名伪ID)是否已有提交,有则返回记录 id,无则 None。
重复提交判定与匿名覆盖判定共用。"""
if not form_id or not student_id:
return None
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('SELECT id FROM submissions WHERE form_id = ? AND student_id = ? LIMIT 1',
(form_id, student_id))
row = cursor.fetchone()
return row['id'] if row else None
def get_last_submission_by_token(form_id, device_token):
"""按设备令牌查找该表单最近一次提交(用于"加载上次填写"),无则返回 None"""
if not form_id or not device_token:
return None
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT * FROM submissions
WHERE form_id = ? AND device_token = ?
ORDER BY submitted_at DESC LIMIT 1
''', (form_id, device_token))
row = cursor.fetchone()
if not row:
return None
return {
'id': row['id'],
'form_id': row['form_id'],
'student_id': row['student_id'],
'student_name': row['student_name'],
'tail': row['tail'],
'submitted_at': row['submitted_at'],
'data': json.loads(row['data']) if row['data'] else {}
}
# ========== 提交历史版本(快照 + 附件归档) ==========
def save_submission_version(form_id, student_id, student_name, tail, data,
is_overwrite=False, ip_address=None, submitted_at=None):
"""归档一次提交事件的内容快照,返回版本 id。每次提交(含覆盖)都会调用。"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
INSERT INTO submission_versions
(form_id, student_id, student_name, tail, data, is_overwrite, ip_address, file_ids, submitted_at)
VALUES (?, ?, ?, ?, ?, ?, ?, '[]', ?)
''', (form_id, student_id, student_name, tail,
json.dumps(data or {}, ensure_ascii=False),
1 if is_overwrite else 0, ip_address,
submitted_at or datetime.now().isoformat()))
return cursor.lastrowid
def update_version_file_ids(version_id, file_ids):
"""记录版本提交时点的文件 id 列表(含沿用保留的旧文件)。"""
clean = [int(f) for f in (file_ids or []) if str(f).strip().lstrip('-').isdigit()]
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('UPDATE submission_versions SET file_ids = ? WHERE id = ?',
(json.dumps(clean), version_id))
def get_prev_version_id(form_id, student_id, before_version_id):
"""该学生此表单在 before_version_id 之前的最新版本 id(无则 None)。"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT MAX(id) AS prev_id FROM submission_versions
WHERE form_id = ? AND student_id = ? AND id < ?
''', (form_id, student_id, before_version_id))
row = cursor.fetchone()
return row['prev_id'] if row and row['prev_id'] else None
def archive_replaced_files(form_id, student_id, keep_file_ids, archive_version_id):
"""覆盖提交时处理旧文件:keep_file_ids 指定的保留为当前文件,
其余归档到 archive_version_id 版本——磁盘文件原地不动,仅在 version_files
中登记引用(元数据转移,零拷贝)。archive_version_id 为 None 时直接删除
(兼容升级前无历史版本的旧数据)。删除范围严格限定在该学生本表单的文件内。"""
keep = {int(f) for f in (keep_file_ids or []) if str(f).strip().lstrip('-').isdigit()}
now = datetime.now().isoformat()
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT id, filename, original_name, file_size, mime_type, file_path, field_name
FROM files
WHERE form_id = ? AND submission_id IN (
SELECT id FROM submissions WHERE form_id = ? AND student_id = ?
)
''', (form_id, form_id, student_id))
for row in cursor.fetchall():
if row['id'] in keep:
continue
if archive_version_id is not None and row['file_path']:
# 磁盘文件保留原位,version_files 登记引用即可
cursor.execute('''
INSERT INTO version_files
(version_id, form_id, original_file_id, filename, original_name,
file_size, mime_type, file_path, file_data, field_name, archived_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (archive_version_id, form_id, row['id'], row['filename'], row['original_name'],
row['file_size'], row['mime_type'], row['file_path'], b'', row['field_name'], now))
elif archive_version_id is not None:
# 极老记录仍以 BLOB 存储(未迁移):拷贝内容归档
cursor.execute('SELECT file_data FROM files WHERE id = ?', (row['id'],))
blob = cursor.fetchone()['file_data'] or b''
cursor.execute('''
INSERT INTO version_files
(version_id, form_id, original_file_id, filename, original_name,
file_size, mime_type, file_path, file_data, field_name, archived_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (archive_version_id, form_id, row['id'], row['filename'], row['original_name'],
row['file_size'], row['mime_type'], None, blob, row['field_name'], now))
cursor.execute('DELETE FROM files WHERE id = ?', (row['id'],))
def _resolve_files_on_cursor(cursor, form_id, file_ids):
"""把版本的 file_ids 解析为文件清单:仍在 files 表的为当前文件,
否则从 version_files 归档中按原始文件 id 找(id 自增不复用,可唯一定位)。"""
result = []
for fid in file_ids:
cursor.execute('''SELECT id, filename, original_name, file_size, mime_type, field_name
FROM files WHERE id = ? AND form_id = ?''', (fid, form_id))
row = cursor.fetchone()
if row:
result.append({
'name': row['original_name'] or row['filename'],
'size': row['file_size'],
'fieldName': row['field_name'],
'archived': False,
'fileId': row['id'],
'downloadUrl': f"/api/download_file/{row['id']}"
})
continue
cursor.execute('''SELECT id, filename, original_name, file_size, mime_type, field_name
FROM version_files WHERE original_file_id = ? AND form_id = ?
ORDER BY id LIMIT 1''', (fid, form_id))
row = cursor.fetchone()
if row:
result.append({
'name': row['original_name'] or row['filename'],
'size': row['file_size'],
'fieldName': row['field_name'],
'archived': True,
'vfileId': row['id'],
'downloadUrl': f"/api/admin/download_version_file/{row['id']}"
})
return result
def get_student_versions(form_id, student_id):
"""某学生此表单的全部历史版本(含解析后的文件清单),按时间倒序。"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT * FROM submission_versions WHERE form_id = ? AND student_id = ?
ORDER BY id DESC
''', (form_id, student_id))
rows = cursor.fetchall()
if not rows:
return []
latest_id = rows[0]['id'] # id 最大即最新
versions = []
for row in rows:
file_ids = json.loads(row['file_ids'] or '[]')
versions.append({
'id': row['id'],
'data': json.loads(row['data']) if row['data'] else {},
'isOverwrite': bool(row['is_overwrite']),
'ip': row['ip_address'],
'submittedAt': row['submitted_at'],
'isLatest': row['id'] == latest_id,
'files': _resolve_files_on_cursor(cursor, form_id, file_ids)
})
return versions
def get_versions_as_of(form_id, as_of_iso):
"""每个学生在 as_of 时间点的最新版本快照(用于按时间点导出)。
返回 {student_id: {'version': {...已解析...}, 'files': [清单]}}。"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT * FROM submission_versions
WHERE form_id = ? AND submitted_at <= ?
ORDER BY id ASC
''', (form_id, as_of_iso))
latest_by_student = {}
for row in cursor.fetchall():
latest_by_student[row['student_id']] = row
result = {}
for student_id, row in latest_by_student.items():
file_ids = json.loads(row['file_ids'] or '[]')
result[student_id] = {
'version': {
'id': row['id'],
'data': json.loads(row['data']) if row['data'] else {},
'is_overwrite': bool(row['is_overwrite']),
'submitted_at': row['submitted_at'],
'student_name': row['student_name'],
'tail': row['tail']
},
'files': _resolve_files_on_cursor(cursor, form_id, file_ids)
}
return result
def get_submission_version(version_id):
"""获取单条版本记录(不含文件清单),用于权限校验与删除前检查。"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('SELECT * FROM submission_versions WHERE id = ?', (version_id,))
row = cursor.fetchone()
if not row:
return None
return {
'id': row['id'],
'form_id': row['form_id'],
'student_id': row['student_id'],
'student_name': row['student_name'],
'submitted_at': row['submitted_at']
}
def get_version_archived_file(vfile_id):
"""获取归档文件(含二进制),用于下载历史版本附件。"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('SELECT * FROM version_files WHERE id = ?', (vfile_id,))
row = cursor.fetchone()
if not row:
return None
return {
'id': row['id'],
'version_id': row['version_id'],
'form_id': row['form_id'],
'filename': row['filename'],
'original_name': row['original_name'],
'file_size': row['file_size'],
'mime_type': row['mime_type'],
'field_name': row['field_name'],
'file_data': _read_file_bytes(row)
}
def delete_submission_version(version_id):
"""删除一条历史版本。
- 非最新条:仅删除该版本快照及其归档附件,当前提交不受影响;
- 最新条:同时清除该学生的当前提交(submissions 记录 + 其现存文件),不自动回滚到旧版本。
返回 {'found': bool, 'deletedCurrent': bool, 'deletedCurrentFiles': n}"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('SELECT * FROM submission_versions WHERE id = ?', (version_id,))
row = cursor.fetchone()
if not row:
return {'found': False}
cursor.execute('''SELECT MAX(id) AS max_id FROM submission_versions
WHERE form_id = ? AND student_id = ?''',
(row['form_id'], row['student_id']))
is_latest = cursor.fetchone()['max_id'] == row['id']
deleted_files = 0
form_id = row['form_id']
student_id = row['student_id']
if is_latest:
# 外键未启用,显式清除当前文件与提交记录
cursor.execute('''
SELECT file_path FROM files
WHERE form_id = ? AND submission_id IN (
SELECT id FROM submissions WHERE form_id = ? AND student_id = ?
)
''', (form_id, form_id, student_id))
paths = [r['file_path'] for r in cursor.fetchall()]
cursor.execute('''
DELETE FROM files
WHERE form_id = ? AND submission_id IN (
SELECT id FROM submissions WHERE form_id = ? AND student_id = ?
)
''', (form_id, form_id, student_id))
deleted_files = cursor.rowcount
for rel in paths:
_unlink_unreferenced(cursor, form_id, rel)
cursor.execute('DELETE FROM submissions WHERE form_id = ? AND student_id = ?',
(form_id, student_id))
# 该版本归档附件:收集引用路径 → 删除记录 → 清理不再被引用的磁盘文件
cursor.execute('SELECT file_path FROM version_files WHERE version_id = ?', (version_id,))
vpaths = [r['file_path'] for r in cursor.fetchall()]
cursor.execute('DELETE FROM version_files WHERE version_id = ?', (version_id,))
for rel in vpaths:
_unlink_unreferenced(cursor, form_id, rel)
cursor.execute('DELETE FROM submission_versions WHERE id = ?', (version_id,))
return {'found': True, 'deletedCurrent': is_latest, 'deletedCurrentFiles': deleted_files}
def delete_submission_files(form_id, student_id):
"""删除提交关联的所有文件"""
with get_db_connection() as conn:
cursor = conn.cursor()
# 获取提交ID
cursor.execute('SELECT id FROM submissions WHERE form_id = ? AND student_id = ?',
(form_id, student_id))
row = cursor.fetchone()
if row:
submission_id = row['id']
cursor.execute('SELECT file_path FROM files WHERE submission_id = ?', (submission_id,))
paths = [r['file_path'] for r in cursor.fetchall()]
# 删除关联文件
cursor.execute('DELETE FROM files WHERE submission_id = ?', (submission_id,))
for rel in paths:
_unlink_unreferenced(cursor, form_id, rel)
# ========== 文件存储相关操作 (BLOB) ==========
def save_file(form_id, file_data, filename, original_name=None, mime_type=None,
field_name=None, submission_id=None):
"""
保存文件到磁盘 data/files/<form_id>/<file_id>.bin,数据库仅存元数据与路径。
大文件不再写入库,多用户并发上传不会长时间占用数据库写锁。
Args:
form_id: 表单ID
file_data: 文件二进制数据 (bytes)
filename: 存储的文件名
original_name: 原始文件名
mime_type: MIME类型
field_name: 表单字段名
submission_id: 关联的提交记录ID
Returns:
file_id: 文件记录ID
"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
INSERT INTO files
(form_id, submission_id, filename, original_name, file_size, mime_type, file_data, uploaded_at, field_name)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
form_id,
submission_id,
filename,
original_name,
len(file_data),
mime_type,
b'', # 内容在磁盘;字段保留 NOT NULL 约束,置 0 字节占位
datetime.now().isoformat(),
field_name
))
file_id = cursor.lastrowid
rel_path = f"{form_id}/{file_id}.bin" # 统一正斜杠,跨平台可迁移
abs_path = _disk_path(rel_path)
try:
os.makedirs(os.path.dirname(abs_path), exist_ok=True)
with open(abs_path, 'wb') as f:
f.write(file_data)
except OSError:
cursor.execute('DELETE FROM files WHERE id = ?', (file_id,))
raise
cursor.execute('UPDATE files SET file_path = ? WHERE id = ?', (rel_path, file_id))
return file_id
def save_file_stream(form_id, file_storage, filename, original_name=None, mime_type=None,
field_name=None, submission_id=None, chunk_size=1024 * 1024):
"""流式把上传文件写到磁盘,全程不把整个文件读进内存。
400MB 级文件用 file.read() 会让单个请求常驻 400MB 内存,同时把「客户端传完 →
服务端响应」的间隔拉长到客户端读超时(表现就是 499 Client Closed Request)。
这里按块搬运:先写 .part 临时文件,fsync 后原子改名,失败则清理行与残留文件。
Returns:
file_id: 文件记录ID
"""
stream = file_storage.stream
# 取大小:FileStorage.stream 是落过盘的临时文件,seek 到末尾是 O(1)
size = 0
try:
stream.seek(0, os.SEEK_END)
size = stream.tell()
stream.seek(0)
except (OSError, AttributeError, ValueError):
size = int(file_storage.content_length or 0)
try:
stream.seek(0)
except (OSError, AttributeError, ValueError):
pass
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute(
"INSERT INTO files "
"(form_id, submission_id, filename, original_name, file_size, mime_type, "
" file_data, uploaded_at, field_name) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
(
form_id,
submission_id,
filename,
original_name,
size,
mime_type,
b"", # 内容在磁盘;字段保留 NOT NULL 约束,置 0 字节占位
datetime.now().isoformat(),
field_name,
),
)
file_id = cursor.lastrowid
rel_path = f"{form_id}/{file_id}.bin"
abs_path = _disk_path(rel_path)
part_path = abs_path + ".part"
written = 0
try:
os.makedirs(os.path.dirname(abs_path), exist_ok=True)
with open(part_path, "wb") as out:
while True:
chunk = stream.read(chunk_size)
if not chunk:
break
out.write(chunk)
written += len(chunk)
out.flush()
os.fsync(out.fileno())
os.replace(part_path, abs_path)
except BaseException:
for path in (part_path, abs_path):
try:
os.remove(path)
except OSError:
pass
cursor.execute("DELETE FROM files WHERE id = ?", (file_id,))
raise
cursor.execute("UPDATE files SET file_path = ?, file_size = ? WHERE id = ?",
(rel_path, written, file_id))
return file_id
def attach_uploaded_file(form_id, src_path, filename, original_name=None, mime_type=None,
field_name=None, submission_id=None):
"""把已经上传并合并好的文件(分片上传的产物)挂到 files 表。
与 save_file_stream 的区别:内容已经在磁盘上,这里只做登记 + 原子移动,
不再复制一遍,所以 400MB 也能瞬间完成。
"""
size = os.path.getsize(src_path)
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute(
"INSERT INTO files "
"(form_id, submission_id, filename, original_name, file_size, mime_type, "
" file_data, uploaded_at, field_name) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
(
form_id,
submission_id,
filename,
original_name,
size,
mime_type,
b"",
datetime.now().isoformat(),
field_name,
),
)
file_id = cursor.lastrowid
rel_path = f"{form_id}/{file_id}.bin"
abs_path = _disk_path(rel_path)
os.makedirs(os.path.dirname(abs_path), exist_ok=True)
try:
# 同一文件系统内 os.replace 是原子且零拷贝;跨设备退化为复制
try:
os.replace(src_path, abs_path)
except OSError:
import shutil
shutil.copyfileobj(open(src_path, 'rb'), open(abs_path, 'wb'), 4 * 1024 * 1024)
os.remove(src_path)
except BaseException:
try:
os.remove(abs_path)
except OSError:
pass
cursor.execute("DELETE FROM files WHERE id = ?", (file_id,))
raise
cursor.execute("UPDATE files SET file_path = ? WHERE id = ?", (rel_path, file_id))
return file_id
def get_file(file_id):
"""获取单个文件(file_data 从磁盘读取)"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('SELECT * FROM files WHERE id = ?', (file_id,))
row = cursor.fetchone()
if row:
return {
'id': row['id'],
'form_id': row['form_id'],
'submission_id': row['submission_id'],
'filename': row['filename'],
'original_name': row['original_name'],
'file_size': row['file_size'],
'mime_type': row['mime_type'],
'file_data': _read_file_bytes(row),
'uploaded_at': row['uploaded_at'],
'field_name': row['field_name']
}
return None
def get_file_by_name(form_id, filename):
"""通过文件名获取文件(file_data 从磁盘读取)"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('SELECT * FROM files WHERE form_id = ? AND filename = ?',
(form_id, filename))
row = cursor.fetchone()
if row:
return {
'id': row['id'],
'form_id': row['form_id'],
'submission_id': row['submission_id'],
'filename': row['filename'],
'original_name': row['original_name'],
'file_size': row['file_size'],
'mime_type': row['mime_type'],
'file_data': _read_file_bytes(row),
'uploaded_at': row['uploaded_at'],
'field_name': row['field_name']
}
return None
def get_form_files(form_id, student_id=None, student_name=None):
"""获取表单的所有文件或特定学生的文件"""
with get_db_connection() as conn:
cursor = conn.cursor()
if student_id and student_name:
# 获取特定学生的文件
cursor.execute('''
SELECT f.* FROM files f
JOIN submissions s ON f.submission_id = s.id
WHERE f.form_id = ? AND s.student_id = ?
''', (form_id, student_id))
else:
# 获取表单所有文件
cursor.execute('SELECT * FROM files WHERE form_id = ?', (form_id,))
rows = cursor.fetchall()
files = []
for row in rows:
files.append({
'id': row['id'],
'form_id': row['form_id'],
'submission_id': row['submission_id'],
'filename': row['filename'],
'original_name': row['original_name'],
'file_size': row['file_size'],
'mime_type': row['mime_type'],
'uploaded_at': row['uploaded_at'],
'field_name': row['field_name'],
'download_url': f"/api/download_file/{row['id']}"
})
return files
def delete_file(file_id):
"""删除文件(含磁盘清理)"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('SELECT file_path, form_id FROM files WHERE id = ?', (file_id,))
row = cursor.fetchone()
rel = row['file_path'] if row else None
form_id = row['form_id'] if row else None
cursor.execute('DELETE FROM files WHERE id = ?', (file_id,))
if rel:
_unlink_unreferenced(cursor, form_id, rel)
def delete_student_files(form_id, student_id, student_name):
"""删除学生的所有文件"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT file_path FROM files
WHERE form_id = ? AND submission_id IN (
SELECT id FROM submissions WHERE form_id = ? AND student_id = ?
)
''', (form_id, form_id, student_id))
paths = [r['file_path'] for r in cursor.fetchall()]
cursor.execute('''
DELETE FROM files
WHERE form_id = ? AND submission_id IN (
SELECT id FROM submissions WHERE form_id = ? AND student_id = ?
)
''', (form_id, form_id, student_id))
for rel in paths:
_unlink_unreferenced(cursor, form_id, rel)
def stream_form_files(form_id, batch_size=1):
"""
流式获取表单文件,每次只加载 batch_size 个文件到内存
用于 ZIP 打包时减少内存占用
Args:
form_id: 表单ID
batch_size: 每批处理的文件数量(默认1个,最低内存占用)
Yields:
dict: 单个文件信息,包含 file_data
"""
with get_db_connection() as conn:
cursor = conn.cursor()
# 先获取所有文件ID列表(只查元数据,不查内容,内存占用极低)
cursor.execute("""
SELECT id, filename, original_name, file_size, field_name, file_path, file_data
FROM files
WHERE form_id = ?
""", (form_id,))
file_rows = cursor.fetchall()
# 逐个从磁盘读取内容
for row in file_rows:
yield {
'id': row['id'],
'filename': row['filename'],
'original_name': row['original_name'],
'file_size': row['file_size'],
'field_name': row['field_name'],
'file_data': _read_file_bytes(row)
}
# 每批处理完后强制垃圾回收
import gc
gc.collect()
def get_form_file_count(form_id):
"""获取表单文件数量(用于快速检查,不加载BLOB)"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('SELECT COUNT(*) as count FROM files WHERE form_id = ?', (form_id,))
return cursor.fetchone()['count']
def get_all_form_files(form_id):
"""获取表单所有文件(包含二进制数据,用于ZIP打包)"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('SELECT * FROM files WHERE form_id = ?', (form_id,))
rows = cursor.fetchall()
files = []
for row in rows:
files.append({
'id': row['id'],
'filename': row['filename'],
'original_name': row['original_name'],
'file_size': row['file_size'],
'file_data': _read_file_bytes(row),
'field_name': row['field_name']
})
return files
# ========== 表单公告附件操作 (BLOB) ==========
def save_announcement_file(form_id, file_data, filename, original_name=None, mime_type=None):
"""保存表单公告附件(BLOB存储,最多3个,超出时抛出异常)"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('SELECT COUNT(*) as count FROM form_announcement_files WHERE form_id = ?', (form_id,))
count = cursor.fetchone()['count']
if count >= 3:
raise ValueError('公告附件最多只能添加3个')
cursor.execute('''
INSERT INTO form_announcement_files
(form_id, filename, original_name, file_size, mime_type, file_data, uploaded_at)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', (
form_id,
filename,
original_name,
len(file_data),
mime_type,
file_data,
datetime.now().isoformat()
))
return cursor.lastrowid
def get_announcement_file(file_id):
"""获取单个公告附件"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('SELECT * FROM form_announcement_files WHERE id = ?', (file_id,))
row = cursor.fetchone()
if row:
return {
'id': row['id'],
'form_id': row['form_id'],
'filename': row['filename'],
'original_name': row['original_name'],
'file_size': row['file_size'],
'mime_type': row['mime_type'],
'file_data': row['file_data'],
'uploaded_at': row['uploaded_at']
}
return None
def get_form_announcement_files(form_id):
"""获取表单的所有公告附件(不含BLOB数据,用于列表展示)"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT id, form_id, filename, original_name, file_size, mime_type, uploaded_at
FROM form_announcement_files WHERE form_id = ? ORDER BY id
''', (form_id,))
rows = cursor.fetchall()
files = []
for row in rows:
files.append({
'id': row['id'],
'form_id': row['form_id'],
'filename': row['filename'],
'original_name': row['original_name'],
'file_size': row['file_size'],
'mime_type': row['mime_type'],
'uploaded_at': row['uploaded_at'],
'download_url': f"/api/announcement_download/{row['id']}"
})
return files
def delete_announcement_file(file_id):
"""删除公告附件"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('DELETE FROM form_announcement_files WHERE id = ?', (file_id,))
def delete_form_announcement_files(form_id):
"""删除表单的所有公告附件"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('DELETE FROM form_announcement_files WHERE form_id = ?', (form_id,))
# ========== 提交历史相关操作 ==========
def record_submission_history(form_id, student_id, submission_type='first', ip_address=None):
"""记录提交历史"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
INSERT INTO submission_history
(form_id, student_id, submission_time, submission_type, ip_address)
VALUES (?, ?, ?, ?, ?)
''', (form_id, student_id, datetime.now().isoformat(), submission_type, ip_address))
def get_submission_history(form_id, student_id=None):
"""获取提交历史"""
with get_db_connection() as conn:
cursor = conn.cursor()
if student_id:
cursor.execute('''
SELECT * FROM submission_history
WHERE form_id = ? AND student_id = ?
ORDER BY submission_time
''', (form_id, student_id))
else:
cursor.execute('''
SELECT * FROM submission_history
WHERE form_id = ?
ORDER BY submission_time
''', (form_id,))
rows = cursor.fetchall()
history = {}
for row in rows:
sid = row['student_id']
if sid not in history:
history[sid] = {
'first_submit': None,
'submissions': []
}
record = {
'time': row['submission_time'],
'type': row['submission_type'],
'ip': row['ip_address']
}
history[sid]['submissions'].append(record)
if row['submission_type'] == 'first' and not history[sid]['first_submit']:
history[sid]['first_submit'] = row['submission_time']
return history
# ========== 统计数据相关操作 ==========
def get_form_stats(form_id):
"""获取表单统计信息"""
with get_db_connection() as conn:
cursor = conn.cursor()
# 提交数量
cursor.execute('SELECT COUNT(*) as count FROM submissions WHERE form_id = ?', (form_id,))
submitted_count = cursor.fetchone()['count']
# 文件数量
cursor.execute('SELECT COUNT(*) as count FROM files WHERE form_id = ?', (form_id,))
file_count = cursor.fetchone()['count']
# 总文件大小
cursor.execute('SELECT COALESCE(SUM(file_size), 0) as total_size FROM files WHERE form_id = ?', (form_id,))
total_size = cursor.fetchone()['total_size']
return {
'submitted_count': submitted_count,
'file_count': file_count,
'total_size': total_size
}
def get_submitted_students(form_id):
"""获取已提交的学生列表"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('SELECT student_id, tail FROM submissions WHERE form_id = ?', (form_id,))
rows = cursor.fetchall()
return {row['tail']: row['student_id'] for row in rows}
def anon_display(pseudo_id):
"""匿名伪ID → (展示名, 短码)。anon_<token> / anon_ip_<hash> 两种形态。"""
if pseudo_id and pseudo_id.startswith('anon_ip_'):
return f'匿名设备(IP) {pseudo_id[8:12]}', pseudo_id[8:12]
short = (pseudo_id or '')[5:9]
return f'匿名设备 {short}', short
def build_status_students(form, submissions=None, versions_map=None):
"""构建管理端统计与导出共用的提交者状态列表。
- 名单模式(有预设):按名单逐人对齐,未提交者也列出
- 匿名模式(无预设):每条提交即一个独立身份(anon_ 伪ID),附 anonymous 标记
versions_map 传入时走"时间点"模式(文件仅含名称/大小清单,无下载地址)。"""
form_id = form.get('id')
preset_id = form.get('presetId')
students = []
if preset_id:
preset = get_preset(preset_id)
if not preset:
return students
verify_digits = preset.get('config', {}).get('verifyDigits', 2)
for s in preset.get('students', []):
student_id = s.get('id', '')
if len(student_id) < verify_digits:
continue
tail = student_id[-verify_digits:]
if versions_map is not None:
entry = versions_map.get(student_id)
students.append({
"tail": tail,
"id": student_id,
"name": s.get('name', ''),
"submitted": entry is not None,
"files": [{'filename': f['name'], 'file_size': f.get('size')}
for f in (entry['files'] if entry else [])],
"data": entry['version']['data'] if entry else {}
})
else:
submission = next(
(sub for sub in submissions if sub['student_id'] == student_id), None)
files = get_form_files(form_id, student_id, s.get('name', ''))
students.append({
"tail": tail,
"id": student_id,
"name": s.get('name', ''),
"submitted": submission is not None,
"files": files,
"data": submission['data'] if submission else {}
})
return students
# 匿名模式
if versions_map is not None:
for pseudo_id, entry in versions_map.items():
display, short = anon_display(pseudo_id)
students.append({
"tail": short,
"id": pseudo_id,
"shortId": short,
"name": display,
"submitted": True,
"anonymous": True,
"files": [{'filename': f['name'], 'file_size': f.get('size')}
for f in entry['files']],
"data": entry['version']['data']
})
else:
for sub in submissions or []:
display, short = anon_display(sub['student_id'])
files = get_form_files(form_id, sub['student_id'], sub['student_name'])
students.append({
"tail": short,
"id": sub['student_id'],
"shortId": short,
"name": display,
"submitted": True,
"anonymous": True,
"files": files,
"data": sub['data']
})
return students
# ========== 清理相关操作 ==========
def cleanup_expired_forms(cutoff_date):
"""清理过期的表单(根据 expires_at 判断,未设置过期时间的永不过期)"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
DELETE FROM forms
WHERE expires_at IS NOT NULL AND expires_at < ?
''', (cutoff_date,))
deleted_count = cursor.rowcount
return deleted_count
def get_expired_forms(cutoff_date):
"""获取过期的表单列表(根据 expires_at 判断,未设置过期时间的永不过期)"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('SELECT id FROM forms WHERE expires_at IS NOT NULL AND expires_at < ?', (cutoff_date,))
return [row['id'] for row in cursor.fetchall()]
# ========== 会话管理相关操作 ==========
def generate_session_id():
"""生成唯一的会话ID"""
import uuid
return uuid.uuid4().hex
def create_session(username, role, ip_address=None, user_agent=None, data=None):
"""
创建新会话,有效期7天
每次访问时过期时间会重置(在验证会话时更新)
"""
session_id = generate_session_id()
now = datetime.now()
expires_at = now + timedelta(days=7) # 7天有效期
session_data = {
'session_id': session_id,
'username': username,
'role': role,
'data': json.dumps(data) if data else '{}',
'created_at': now.isoformat(),
'expires_at': expires_at.isoformat(),
'last_access_at': now.isoformat(),
'ip_address': ip_address,
'user_agent': user_agent
}
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
INSERT INTO sessions
(session_id, username, role, data, created_at, expires_at, last_access_at, ip_address, user_agent)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
session_data['session_id'],
session_data['username'],
session_data['role'],
session_data['data'],
session_data['created_at'],
session_data['expires_at'],
session_data['last_access_at'],
session_data['ip_address'],
session_data['user_agent']
))
conn.commit()
return session_data
def get_session(session_id):
"""
获取会话信息,如果会话有效则自动续期(重置过期时间为7天后)
"""
if not session_id:
return None
now = datetime.now()
with get_db_connection() as conn:
cursor = conn.cursor()
# 查询会话
cursor.execute('''
SELECT * FROM sessions
WHERE session_id = ? AND expires_at > ?
''', (session_id, now.isoformat()))
row = cursor.fetchone()
if not row:
return None
session = dict(row)
# 自动续期:更新过期时间为7天后,并更新最后访问时间
new_expires_at = now + timedelta(days=7)
new_last_access = now.isoformat()
cursor.execute('''
UPDATE sessions
SET expires_at = ?, last_access_at = ?
WHERE session_id = ?
''', (new_expires_at.isoformat(), new_last_access, session_id))
conn.commit()
# 更新返回的会话数据
session['expires_at'] = new_expires_at.isoformat()
session['last_access_at'] = new_last_access
# 解析JSON数据
try:
session['data'] = json.loads(session.get('data', '{}'))
except:
session['data'] = {}
return session
return None
def delete_session(session_id):
"""删除指定会话(登出时使用)"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('DELETE FROM sessions WHERE session_id = ?', (session_id,))
conn.commit()
return cursor.rowcount > 0
def delete_user_sessions(username):
"""删除用户的所有会话(用户被删除或密码修改时使用)"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('DELETE FROM sessions WHERE username = ?', (username,))
conn.commit()
return cursor.rowcount
def cleanup_expired_sessions():
"""清理所有过期的会话(可作为定时任务运行)"""
now = datetime.now().isoformat()
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('DELETE FROM sessions WHERE expires_at < ?', (now,))
conn.commit()
deleted_count = cursor.rowcount
if deleted_count > 0:
print(f"🧹 清理了 {deleted_count} 个过期会话")
return deleted_count
def get_user_sessions(username):
"""获取用户的所有活跃会话"""
now = datetime.now().isoformat()
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT session_id, created_at, expires_at, last_access_at, ip_address
FROM sessions
WHERE username = ? AND expires_at > ?
ORDER BY last_access_at DESC
''', (username, now))
rows = cursor.fetchall()
return [dict(row) for row in rows]
def get_all_active_sessions():
"""获取所有活跃会话(仅管理员使用)"""
now = datetime.now().isoformat()
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT s.*, u.role as user_role
FROM sessions s
LEFT JOIN users u ON s.username = u.username
WHERE s.expires_at > ?
ORDER BY s.last_access_at DESC
''', (now,))
rows = cursor.fetchall()
return [dict(row) for row in rows]
# ========== 监控数据相关操作 ==========
def init_monitor_tables():
"""初始化监控相关表(如果不存在则创建)"""
with get_db_connection() as conn:
cursor = conn.cursor()
# 系统性能指标快照(每分钟采集一次)
cursor.execute('''
CREATE TABLE IF NOT EXISTS system_metrics (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TEXT NOT NULL,
cpu_percent REAL,
memory_used INTEGER,
disk_read_bytes INTEGER,
disk_write_bytes INTEGER,
net_sent_bytes INTEGER,
net_recv_bytes INTEGER,
active_requests INTEGER,
online_users INTEGER
)
''')
# API 调用统计(按分钟聚合)
cursor.execute('''
CREATE TABLE IF NOT EXISTS api_stats (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TEXT NOT NULL,
endpoint TEXT,
method TEXT,
count INTEGER DEFAULT 0,
total_time_ms INTEGER DEFAULT 0,
errors INTEGER DEFAULT 0,
bytes_in INTEGER DEFAULT 0,
bytes_out INTEGER DEFAULT 0
)
''')
# 业务指标(按小时聚合)
cursor.execute('''
CREATE TABLE IF NOT EXISTS business_metrics (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TEXT NOT NULL,
metric_name TEXT,
metric_value REAL
)
''')
# 创建索引
cursor.execute('CREATE INDEX IF NOT EXISTS idx_metrics_timestamp ON system_metrics(timestamp)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_api_stats_timestamp ON api_stats(timestamp)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_business_metrics_time ON business_metrics(timestamp)')
conn.commit()
print("✅ 监控数据表初始化完成")
def insert_system_metrics(cpu_percent, memory_used,
disk_read_bytes, disk_write_bytes,
net_sent_bytes, net_recv_bytes,
active_requests, online_users):
"""插入系统性能指标"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
INSERT INTO system_metrics
(timestamp, cpu_percent, memory_used,
disk_read_bytes, disk_write_bytes, net_sent_bytes, net_recv_bytes,
active_requests, online_users)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
datetime.now().isoformat(),
cpu_percent, memory_used,
disk_read_bytes, disk_write_bytes,
net_sent_bytes, net_recv_bytes,
active_requests, online_users
))
def insert_api_stat(endpoint, method, time_ms, has_error, bytes_in, bytes_out):
"""插入或更新 API 调用统计(按分钟聚合)"""
now = datetime.now()
# 按分钟截断时间戳
minute_ts = now.replace(second=0, microsecond=0).isoformat()
with get_db_connection() as conn:
cursor = conn.cursor()
# 尝试更新已存在的记录
cursor.execute('''
UPDATE api_stats
SET count = count + 1,
total_time_ms = total_time_ms + ?,
errors = errors + ?,
bytes_in = bytes_in + ?,
bytes_out = bytes_out + ?
WHERE timestamp = ? AND endpoint = ? AND method = ?
''', (time_ms, 1 if has_error else 0, bytes_in, bytes_out,
minute_ts, endpoint, method))
if cursor.rowcount == 0:
# 插入新记录
cursor.execute('''
INSERT INTO api_stats
(timestamp, endpoint, method, count, total_time_ms, errors, bytes_in, bytes_out)
VALUES (?, ?, ?, 1, ?, ?, ?, ?)
''', (minute_ts, endpoint, method, time_ms,
1 if has_error else 0, bytes_in, bytes_out))
def insert_business_metric(metric_name, metric_value):
"""插入业务指标(固定按 5m 对齐)"""
now = datetime.now()
# 固定按 5m 对齐
aligned_minutes = (now.minute // 5) * 5
aligned_ts = now.replace(minute=aligned_minutes, second=0, microsecond=0).isoformat()
with get_db_connection() as conn:
cursor = conn.cursor()
# 累加同一 5m 窗口内的业务指标
cursor.execute('''
UPDATE business_metrics
SET metric_value = metric_value + ?
WHERE timestamp = ? AND metric_name = ?
''', (metric_value, aligned_ts, metric_name))
if cursor.rowcount == 0:
cursor.execute('''
INSERT INTO business_metrics (timestamp, metric_name, metric_value)
VALUES (?, ?, ?)
''', (aligned_ts, metric_name, metric_value))
def get_system_metrics_history(start_time, end_time, granularity='5m'):
"""获取系统指标历史数据,支持降采样"""
# 将 granularity 转换为分钟数
granularity_minutes = {
'1m': 1, '5m': 5, '10m': 10, '15m': 15,
'30m': 30, '1h': 60, '2h': 120,
'6h': 360, '12h': 720, '1d': 1440
}.get(granularity, 5)
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT timestamp, cpu_percent, memory_used,
disk_read_bytes, disk_write_bytes, net_sent_bytes, net_recv_bytes,
active_requests, online_users
FROM system_metrics
WHERE timestamp >= ? AND timestamp <= ?
ORDER BY timestamp ASC
''', (start_time, end_time))
rows = cursor.fetchall()
if not rows:
return []
# 降采样:将数据聚合到指定粒度
result = []
if granularity_minutes <= 1:
# 不需要降采样
for row in rows:
result.append(dict(row))
else:
# 按时间窗口聚合
from collections import defaultdict
buckets = defaultdict(list)
for row in rows:
try:
ts = datetime.fromisoformat(row['timestamp'])
# 将时间戳对齐到粒度窗口
aligned_minutes = (ts.minute // granularity_minutes) * granularity_minutes
bucket_ts = ts.replace(minute=aligned_minutes, second=0, microsecond=0)
buckets[bucket_ts.isoformat()].append(dict(row))
except:
pass
for bucket_ts in sorted(buckets.keys()):
bucket_rows = buckets[bucket_ts]
# 取平均值
avg = {
'timestamp': bucket_ts,
'cpu_percent': sum(r['cpu_percent'] or 0 for r in bucket_rows) / len(bucket_rows),
'memory_used': sum(r['memory_used'] or 0 for r in bucket_rows) / len(bucket_rows),
'disk_read_bytes': sum(r['disk_read_bytes'] or 0 for r in bucket_rows) / len(bucket_rows),
'disk_write_bytes': sum(r['disk_write_bytes'] or 0 for r in bucket_rows) / len(bucket_rows),
'net_sent_bytes': sum(r['net_sent_bytes'] or 0 for r in bucket_rows) / len(bucket_rows),
'net_recv_bytes': sum(r['net_recv_bytes'] or 0 for r in bucket_rows) / len(bucket_rows),
'active_requests': sum(r['active_requests'] or 0 for r in bucket_rows) / len(bucket_rows),
'online_users': bucket_rows[-1]['online_users'] or 0,
}
result.append(avg)
return result
def get_api_stats_history(start_time, end_time):
"""获取 API 调用统计历史"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT timestamp,
SUM(count) as total_count,
SUM(total_time_ms) as total_time,
SUM(errors) as total_errors
FROM api_stats
WHERE timestamp >= ? AND timestamp <= ?
GROUP BY timestamp
ORDER BY timestamp ASC
''', (start_time, end_time))
return [dict(row) for row in cursor.fetchall()]
def get_business_metrics_history(start_time, end_time, granularity='5m'):
"""获取业务指标历史数据,支持降采样"""
# 将 granularity 转换为分钟数
granularity_minutes = {
'1m': 1, '5m': 5, '10m': 10, '15m': 15,
'30m': 30, '1h': 60, '2h': 120,
'6h': 360, '12h': 720, '1d': 1440
}.get(granularity, 5)
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT timestamp, metric_name, metric_value
FROM business_metrics
WHERE timestamp >= ? AND timestamp <= ?
ORDER BY timestamp ASC
''', (start_time, end_time))
rows = cursor.fetchall()
if not rows:
return []
# 降采样:按粒度聚合
if granularity_minutes <= 1:
# 不需要降采样
return [dict(row) for row in rows]
else:
from collections import defaultdict
buckets = defaultdict(list)
for row in rows:
try:
ts = datetime.fromisoformat(row['timestamp'])
aligned_minutes = (ts.minute // granularity_minutes) * granularity_minutes
bucket_ts = ts.replace(minute=aligned_minutes, second=0, microsecond=0)
buckets[bucket_ts.isoformat()].append(dict(row))
except:
pass
result = []
for bucket_ts in sorted(buckets.keys()):
bucket_rows = buckets[bucket_ts]
# 同一粒度窗口内的指标先按 metric_name 分组再累加
grouped = defaultdict(float)
for r in bucket_rows:
name = r['metric_name']
grouped[name] += r['metric_value'] or 0
for name, total in grouped.items():
result.append({
'timestamp': bucket_ts,
'metric_name': name,
'total_value': total
})
return result
def cleanup_monitor_data(before_date):
"""清理指定日期之前的监控数据"""
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('DELETE FROM system_metrics WHERE timestamp < ?', (before_date,))
metrics_deleted = cursor.rowcount
cursor.execute('DELETE FROM api_stats WHERE timestamp < ?', (before_date,))
api_deleted = cursor.rowcount
cursor.execute('DELETE FROM business_metrics WHERE timestamp < ?', (before_date,))
business_deleted = cursor.rowcount
total = metrics_deleted + api_deleted + business_deleted
conn.commit()
return total
def get_online_users_count():
"""获取当前在线用户数(基于有效会话)"""
now = datetime.now().isoformat()
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT COUNT(DISTINCT username) as count
FROM sessions
WHERE expires_at > ?
''', (now,))
row = cursor.fetchone()
return row['count'] if row else 0
# 初始化数据库
if __name__ == '__main__':
init_database()