import json import os from datetime import datetime class Student: def __init__(self, student_id, name, class_name, total_score=0): self.student_id = student_id self.name = name self.class_name = class_name self.total_score = total_score def to_dict(self): return { 'student_id': self.student_id, 'name': self.name, 'class_name': self.class_name, 'total_score': self.total_score } class RollCallRecord: def __init__(self, record_id, student_id, student_name, call_time, score_change=0): self.record_id = record_id self.student_id = student_id self.student_name = student_name self.call_time = call_time self.score_change = score_change def to_dict(self): return { 'record_id': self.record_id, 'student_id': self.student_id, 'student_name': self.student_name, 'call_time': self.call_time, 'score_change': self.score_change } class Database: def __init__(self): self.students_file = 'data/students.json' self.records_file = 'data/records.json' self._ensure_data_directory() self._initialize_data() def _ensure_data_directory(self): os.makedirs('data', exist_ok=True) def _initialize_data(self): # 初始化示例数据 if not os.path.exists(self.students_file): sample_students = [ Student("2024001", "张三", "软工K班").to_dict(), Student("2024002", "李四", "软工K班").to_dict(), Student("2024003", "王五", "软工K班").to_dict(), Student("2024004", "赵六", "软工K班").to_dict(), Student("2024005", "钱七", "软工K班").to_dict() ] self._save_json(self.students_file, sample_students) if not os.path.exists(self.records_file): self._save_json(self.records_file, []) def _load_json(self, filename): try: with open(filename, 'r', encoding='utf-8') as f: return json.load(f) except: return [] def _save_json(self, filename, data): with open(filename, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) def get_all_students(self): data = self._load_json(self.students_file) return [Student(**item) for item in data] def get_students_by_class(self, class_name): students = self.get_all_students() return [s for s in students if s.class_name == class_name] def update_student_score(self, student_id, score_delta): students = self.get_all_students() for student in students: if student.student_id == student_id: student.total_score += score_delta break # 保存更新 self._save_json(self.students_file, [s.to_dict() for s in students]) return True def add_roll_call_record(self, student_id, student_name, score_change=0): records = self._load_json(self.records_file) new_record = RollCallRecord( record_id=len(records) + 1, student_id=student_id, student_name=student_name, call_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"), score_change=score_change ) records.append(new_record.to_dict()) self._save_json(self.records_file, records) return new_record def get_recent_records(self, limit=10): records = self._load_json(self.records_file) return records[-limit:][::-1] # 返回最新的记录