Files
zlqy/fix_question_ids.py

67 lines
2.1 KiB
Python
Raw Permalink 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.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
修复考试题目ID不连续的问题
重新为所有考试的题目分配连续的ID
"""
from app import app, db
from models import Exam
import json
def fix_question_ids():
"""修复所有考试的题目ID使其连续"""
with app.app_context():
exams = Exam.query.all()
fixed_count = 0
for exam in exams:
try:
# 获取题目列表
if exam.is_encrypted and exam.encrypted_questions:
from app import decrypt_questions
questions = json.loads(decrypt_questions(exam.encrypted_questions))
else:
questions = exam.get_questions()
if not questions:
continue
# 检查ID是否连续
needs_fix = False
for idx, q in enumerate(questions, 1):
if q.get('id') != idx:
needs_fix = True
break
if needs_fix:
# 重新分配连续的ID
for idx, q in enumerate(questions, 1):
q['id'] = idx
# 保存修复后的题目
questions_json = json.dumps(questions)
exam.set_questions(questions)
if exam.is_encrypted:
from app import encrypt_questions
exam.encrypted_questions = encrypt_questions(questions_json)
fixed_count += 1
print(f"修复考试 #{exam.id}: {exam.title}")
except Exception as e:
print(f"处理考试 #{exam.id} 时出错: {e}")
continue
if fixed_count > 0:
db.session.commit()
print(f"\n总共修复了 {fixed_count} 份考试")
else:
print("\n没有需要修复的考试")
if __name__ == '__main__':
print("开始修复考试题目ID...")
fix_question_ids()
print("修复完成!")