#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sqlite3 import json import uuid from datetime import datetime, timezone, timedelta from http.server import HTTPServer, BaseHTTPRequestHandler from urllib.parse import urlparse, parse_qs import cgi def get_east8_time_string(): """获取东八区时间字符串格式,用于数据库存储""" east8_tz = timezone(timedelta(hours=8)) return datetime.now(east8_tz).strftime('%Y-%m-%d %H:%M:%S') class SurveyAPI: def __init__(self, db_path='data/survey.db'): self.db_path = db_path def get_connection(self): conn = sqlite3.connect(self.db_path) conn.row_factory = sqlite3.Row return conn def create_student(self, name, school, grade, phone, selected_tag=''): """创建学员记录""" student_id = str(uuid.uuid4()) conn = self.get_connection() cursor = conn.cursor() cursor.execute(''' INSERT INTO students (id, name, school, grade, phone, selected_tag) VALUES (?, ?, ?, ?, ?, ?) ''', (student_id, name, school, grade, phone, selected_tag)) conn.commit() conn.close() return student_id def create_quiz_session(self, student_id, questions_config): """创建答题会话""" session_id = str(uuid.uuid4()) conn = self.get_connection() cursor = conn.cursor() cursor.execute(''' INSERT INTO quiz_sessions (id, student_id, questions_config, status) VALUES (?, ?, ?, 'created') ''', (session_id, student_id, json.dumps(questions_config))) conn.commit() conn.close() return session_id def save_answers(self, session_id, answers): """保存答题结果""" conn = self.get_connection() cursor = conn.cursor() total_score = 0 for answer in answers: answer_id = str(uuid.uuid4()) user_answer = answer.get('user_answer', '') correct_answer = answer.get('correct_answer', '') is_correct = user_answer == correct_answer score = answer['score'] if is_correct else 0 total_score += score cursor.execute(''' INSERT INTO quiz_answers (id, session_id, question_id, question_text, question_type, user_answer, correct_answer, is_correct, score) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ''', (answer_id, session_id, answer.get('question_id', ''), answer.get('question_text', ''), answer.get('question_type', ''), user_answer, correct_answer, is_correct, score)) # 更新会话状态 cursor.execute(''' UPDATE quiz_sessions SET status = 'completed', total_score = ?, completed_at = ? WHERE id = ? ''', (total_score, get_east8_time_string(), session_id)) conn.commit() conn.close() return total_score class SurveyHandler(BaseHTTPRequestHandler): def __init__(self, *args, **kwargs): self.api = SurveyAPI() super().__init__(*args, **kwargs) def do_OPTIONS(self): """处理预检请求""" self.send_response(200) self.send_header('Access-Control-Allow-Origin', '*') self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS') self.send_header('Access-Control-Allow-Headers', 'Content-Type') self.end_headers() def send_cors_headers(self): """发送CORS头""" self.send_header('Access-Control-Allow-Origin', '*') self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS') self.send_header('Access-Control-Allow-Headers', 'Content-Type') def do_POST(self): """处理POST请求""" parsed_path = urlparse(self.path) path = parsed_path.path try: if path == '/api/create-session': self.handle_create_session() elif path == '/api/save-answers': self.handle_save_answers() else: self.send_error(404, "API endpoint not found") except Exception as e: self.send_error(500, str(e)) def handle_create_session(self): """创建答题会话""" content_length = int(self.headers['Content-Length']) post_data = self.rfile.read(content_length) data = json.loads(post_data.decode('utf-8')) name = data.get('name', '').strip() school = data.get('school', '').strip() grade = data.get('grade', '').strip() phone = data.get('phone', '').strip() selected_subject = data.get('selectedSubject', '').strip() selected_semester = data.get('selectedSemester', '').strip() selected_exam_type = data.get('selectedExamType', '').strip() # 构建描述性标签 selected_tag = "" if selected_subject and grade and selected_semester and selected_exam_type: selected_tag = f"{selected_subject}-{grade}{selected_semester}-{selected_exam_type}考试" elif selected_subject and grade and selected_semester: selected_tag = f"{selected_subject}-{grade}{selected_semester}" elif selected_subject and grade: selected_tag = f"{selected_subject}-{grade}" elif selected_subject: selected_tag = selected_subject questions_config = data.get('questionsConfig', {}) if not name or not school or not grade or not phone: self.send_error(400, "姓名、学校、年级和手机号不能为空") return # 创建学员记录 student_id = self.api.create_student(name, school, grade, phone, selected_tag) # 创建答题会话 session_id = self.api.create_quiz_session(student_id, questions_config) response = { 'success': True, 'sessionId': session_id, 'studentId': student_id } self.send_response(200) self.send_header('Content-Type', 'application/json') self.send_cors_headers() self.end_headers() self.wfile.write(json.dumps(response, ensure_ascii=False).encode('utf-8')) def handle_save_answers(self): """保存答题结果""" content_length = int(self.headers['Content-Length']) post_data = self.rfile.read(content_length) data = json.loads(post_data.decode('utf-8')) session_id = data.get('sessionId') answers = data.get('answers', []) if not session_id or not answers: self.send_error(400, "会话ID和答题结果不能为空") return print(f"Debug: session_id = {session_id}") print(f"Debug: answers count = {len(answers)}") print(f"Debug: first answer keys = {list(answers[0].keys()) if answers else 'None'}") total_score = self.api.save_answers(session_id, answers) response = { 'success': True, 'totalScore': total_score } self.send_response(200) self.send_header('Content-Type', 'application/json') self.send_cors_headers() self.end_headers() self.wfile.write(json.dumps(response, ensure_ascii=False).encode('utf-8')) def do_GET(self): """处理GET请求""" parsed_path = urlparse(self.path) path = parsed_path.path try: if path.startswith('/quiz/'): self.handle_quiz_page(path) else: self.send_error(404, "Page not found") except Exception as e: self.send_error(500, str(e)) def handle_quiz_page(self, path): """处理答题页面""" session_id = path.split('/')[-1] if not session_id: self.send_error(400, "Session ID is required") return # 验证会话是否存在 conn = self.api.get_connection() cursor = conn.cursor() cursor.execute(''' SELECT s.*, qs.questions_config, qs.status FROM students s JOIN quiz_sessions qs ON s.id = qs.student_id WHERE qs.id = ? ''', (session_id,)) session_data = cursor.fetchone() conn.close() if not session_data: self.send_error(404, "Session not found") return # 生成答题页面HTML html_content = self.generate_quiz_page(session_data) self.send_response(200) self.send_header('Content-Type', 'text/html; charset=utf-8') self.send_cors_headers() self.end_headers() self.wfile.write(html_content.encode('utf-8')) def generate_quiz_page(self, session_data): """生成答题页面HTML""" questions_config = json.loads(session_data['questions_config']) student_name = session_data['name'] school = session_data['school'] grade = session_data['grade'] phone = session_data['phone'] return f'''
请认真回答以下问题