初版:上传接口(从线上实例导出,适配容器端口)
This commit is contained in:
@@ -0,0 +1,210 @@
|
||||
"""
|
||||
数据迁移脚本 - 将旧版文件系统数据迁移到SQLite数据库
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import sqlite3
|
||||
from datetime import datetime
|
||||
from database import init_database, get_db_connection, save_form, save_preset, save_user, save_submission, save_file
|
||||
|
||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
FORMS_DIR = os.path.join(BASE_DIR, 'forms')
|
||||
PRESETS_DIR = os.path.join(BASE_DIR, 'presets')
|
||||
UPLOAD_BASE_FOLDER = os.path.join(BASE_DIR, 'uploads')
|
||||
USERS_FILE = os.path.join(BASE_DIR, 'users.json')
|
||||
|
||||
def migrate_users():
|
||||
"""迁移用户数据"""
|
||||
print("迁移用户数据...")
|
||||
if not os.path.exists(USERS_FILE):
|
||||
print(" 用户文件不存在,跳过")
|
||||
return
|
||||
|
||||
try:
|
||||
with open(USERS_FILE, 'r', encoding='utf-8') as f:
|
||||
users = json.load(f)
|
||||
|
||||
for username, user_data in users.items():
|
||||
save_user(username, user_data)
|
||||
print(f" 已迁移用户: {username}")
|
||||
|
||||
print(f"✅ 用户数据迁移完成,共 {len(users)} 个用户")
|
||||
except Exception as e:
|
||||
print(f"❌ 用户数据迁移失败: {e}")
|
||||
|
||||
|
||||
def migrate_forms():
|
||||
"""迁移表单配置"""
|
||||
print("迁移表单配置...")
|
||||
if not os.path.exists(FORMS_DIR):
|
||||
print(" 表单目录不存在,跳过")
|
||||
return
|
||||
|
||||
count = 0
|
||||
for filename in os.listdir(FORMS_DIR):
|
||||
if not filename.endswith('.json'):
|
||||
continue
|
||||
|
||||
try:
|
||||
filepath = os.path.join(FORMS_DIR, filename)
|
||||
with open(filepath, 'r', encoding='utf-8') as f:
|
||||
form_config = json.load(f)
|
||||
|
||||
save_form(form_config)
|
||||
print(f" 已迁移表单: {form_config.get('id')} - {form_config.get('title', '未命名')}")
|
||||
count += 1
|
||||
except Exception as e:
|
||||
print(f" ❌ 迁移表单失败 {filename}: {e}")
|
||||
|
||||
print(f"✅ 表单配置迁移完成,共 {count} 个表单")
|
||||
|
||||
|
||||
def migrate_presets():
|
||||
"""迁移预设数据"""
|
||||
print("迁移预设数据...")
|
||||
if not os.path.exists(PRESETS_DIR):
|
||||
print(" 预设目录不存在,跳过")
|
||||
return
|
||||
|
||||
count = 0
|
||||
for filename in os.listdir(PRESETS_DIR):
|
||||
if not filename.endswith('.json'):
|
||||
continue
|
||||
|
||||
try:
|
||||
filepath = os.path.join(PRESETS_DIR, filename)
|
||||
with open(filepath, 'r', encoding='utf-8') as f:
|
||||
preset_data = json.load(f)
|
||||
|
||||
save_preset(preset_data)
|
||||
print(f" 已迁移预设: {preset_data.get('id')} - {preset_data.get('name', '未命名')}")
|
||||
count += 1
|
||||
except Exception as e:
|
||||
print(f" ❌ 迁移预设失败 {filename}: {e}")
|
||||
|
||||
print(f"✅ 预设数据迁移完成,共 {count} 个预设")
|
||||
|
||||
|
||||
def migrate_submissions_and_files():
|
||||
"""迁移提交记录和文件"""
|
||||
print("迁移提交记录和文件...")
|
||||
|
||||
if not os.path.exists(UPLOAD_BASE_FOLDER):
|
||||
print(" 上传目录不存在,跳过")
|
||||
return
|
||||
|
||||
total_files = 0
|
||||
for form_id in os.listdir(UPLOAD_BASE_FOLDER):
|
||||
form_upload_dir = os.path.join(UPLOAD_BASE_FOLDER, form_id)
|
||||
if not os.path.isdir(form_upload_dir):
|
||||
continue
|
||||
|
||||
# 处理提交记录文件 (submitted.txt)
|
||||
submitted_file = os.path.join(form_upload_dir, 'submitted.txt')
|
||||
if os.path.exists(submitted_file):
|
||||
try:
|
||||
with open(submitted_file, 'r', encoding='utf-8') as f:
|
||||
submitted_tails = [line.strip() for line in f if line.strip()]
|
||||
|
||||
# 获取表单配置以查找学生信息
|
||||
from database import get_form, get_preset
|
||||
form = get_form(form_id)
|
||||
if form:
|
||||
preset_id = form.get('presetId')
|
||||
preset = get_preset(preset_id) if preset_id else None
|
||||
|
||||
for tail in submitted_tails:
|
||||
# 查找学生信息
|
||||
student_id = None
|
||||
student_name = None
|
||||
|
||||
if preset:
|
||||
verify_digits = preset.get('config', {}).get('verifyDigits', 2)
|
||||
for s in preset.get('students', []):
|
||||
sid = s.get('id', '')
|
||||
if len(sid) >= verify_digits and sid[-verify_digits:] == tail:
|
||||
student_id = sid
|
||||
student_name = s.get('name', '')
|
||||
break
|
||||
|
||||
if student_id and student_name:
|
||||
save_submission(form_id, student_id, student_name, tail)
|
||||
print(f" 已迁移提交记录: {form_id} - {student_name} ({tail})")
|
||||
except Exception as e:
|
||||
print(f" ❌ 迁移提交记录失败 {form_id}: {e}")
|
||||
|
||||
# 迁移文件
|
||||
for filename in os.listdir(form_upload_dir):
|
||||
if filename in ['submitted.txt', 'time.json'] or filename.startswith('.'):
|
||||
continue
|
||||
|
||||
file_path = os.path.join(form_upload_dir, filename)
|
||||
if not os.path.isfile(file_path):
|
||||
continue
|
||||
|
||||
try:
|
||||
with open(file_path, 'rb') as f:
|
||||
file_data = f.read()
|
||||
|
||||
# 从文件名解析学生信息
|
||||
# 格式: 姓名学号.扩展名 或 姓名学号_字段名.扩展名
|
||||
name_part = filename.rsplit('.', 1)[0] # 去掉扩展名
|
||||
field_name = None
|
||||
|
||||
if '_' in name_part:
|
||||
parts = name_part.rsplit('_', 1)
|
||||
name_part = parts[0]
|
||||
field_name = parts[1]
|
||||
|
||||
save_file(
|
||||
form_id=form_id,
|
||||
file_data=file_data,
|
||||
filename=filename,
|
||||
original_name=filename,
|
||||
field_name=field_name
|
||||
)
|
||||
print(f" 已迁移文件: {form_id}/{filename} ({len(file_data)} bytes)")
|
||||
total_files += 1
|
||||
except Exception as e:
|
||||
print(f" ❌ 迁移文件失败 {filename}: {e}")
|
||||
|
||||
print(f"✅ 文件迁移完成,共 {total_files} 个文件")
|
||||
|
||||
|
||||
def main():
|
||||
"""主迁移函数"""
|
||||
print("=" * 60)
|
||||
print("数据迁移工具 - 文件系统到SQLite数据库")
|
||||
print("=" * 60)
|
||||
print()
|
||||
|
||||
# 初始化数据库
|
||||
print("初始化数据库...")
|
||||
init_database()
|
||||
print()
|
||||
|
||||
# 执行迁移
|
||||
migrate_users()
|
||||
print()
|
||||
|
||||
migrate_forms()
|
||||
print()
|
||||
|
||||
migrate_presets()
|
||||
print()
|
||||
|
||||
migrate_submissions_and_files()
|
||||
print()
|
||||
|
||||
print("=" * 60)
|
||||
print("迁移完成!")
|
||||
print("=" * 60)
|
||||
print()
|
||||
print("注意:")
|
||||
print("1. 旧数据仍然保留在原位置,不会自动删除")
|
||||
print("2. 请验证新系统正常工作后再手动删除旧数据")
|
||||
print("3. 数据库文件位置:", os.path.join(BASE_DIR, 'app.db'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user