rairo commited on
Commit
b0ce3c2
·
verified ·
1 Parent(s): 8192a2e

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +38 -34
main.py CHANGED
@@ -822,67 +822,71 @@ def submit_quiz_attempt(quiz_id):
822
 
823
  try:
824
  data = request.get_json()
825
- user_answers = data.get('answers') # Expected format: { "0": "A", "1": "C", ... } (index as string key)
826
 
827
  if not isinstance(user_answers, dict):
828
  return jsonify({'error': 'answers must be provided as a JSON object'}), 400
829
 
830
- # --- Fetch Quiz Data (including correct answers) ---
831
- quiz_res = supabase.table('quizzes').select('questions, user_id').eq('id', quiz_id).maybe_single().execute()
 
 
 
 
 
832
  if not quiz_res.data:
833
  return jsonify({'error': 'Quiz not found'}), 404
834
- # Optional: Check if user owns the quiz, though submitting attempts might be allowed more broadly
835
- # if quiz_res.data['user_id'] != user.id:
836
- # return jsonify({'error': 'Cannot submit attempt for this quiz'}), 403
837
 
838
- quiz_questions = json.loads(quiz_res.data['questions']) # Load JSONB data
 
 
839
 
840
- # --- Calculate Score ---
841
  correct_count = 0
842
  total_questions = len(quiz_questions)
843
- feedback = {} # Optional: Provide feedback on each question
844
-
845
- for index, question_data in enumerate(quiz_questions):
846
- q_index_str = str(index)
847
- correct_answer = question_data.get('correct_answer')
848
- user_answer = user_answers.get(q_index_str)
849
-
850
- is_correct = (user_answer == correct_answer)
851
- if is_correct:
852
- correct_count += 1
853
-
854
- feedback[q_index_str] = {
855
- "correct": is_correct,
856
- "correct_answer": correct_answer,
857
- "user_answer": user_answer
858
- }
 
 
 
859
 
860
  score = (correct_count / total_questions) * 100 if total_questions > 0 else 0.0
861
 
862
- # --- Save Quiz Attempt ---
863
  attempt_res = supabase.table('quiz_attempts').insert({
864
  'quiz_id': str(quiz_id),
865
  'user_id': user.id,
866
  'score': score,
867
- 'answers': json.dumps(user_answers) # Save user's submitted answers
868
  }).execute()
869
- if not attempt_res.data: raise Exception(f"Failed to save quiz attempt: {attempt_res.error}")
870
- attempt_id = attempt_res.data[0]['id']
871
 
872
  return jsonify({
873
  'success': True,
874
- 'attempt_id': attempt_id,
875
  'score': round(score, 2),
876
  'correct_count': correct_count,
877
  'total_questions': total_questions,
878
- 'feedback': feedback # Return feedback for the user interface
 
879
  }), 201
880
 
881
- except json.JSONDecodeError:
882
- return jsonify({'error': 'Invalid format for quiz questions data in database.'}), 500
883
  except Exception as e:
884
- logging.error(f"Unexpected error submitting quiz attempt for user {user.id}, quiz {quiz_id}: {traceback.format_exc()}")
885
- return jsonify({'error': f'An unexpected error occurred: {e}'}), 500
886
 
887
 
888
 
 
822
 
823
  try:
824
  data = request.get_json()
825
+ user_answers = data.get('answers') # Expected format: { "questionId": "A", ... }
826
 
827
  if not isinstance(user_answers, dict):
828
  return jsonify({'error': 'answers must be provided as a JSON object'}), 400
829
 
830
+ # Fetch Quiz Data
831
+ quiz_res = supabase.table('quizzes')\
832
+ .select('questions, user_id')\
833
+ .eq('id', quiz_id)\
834
+ .maybe_single()\
835
+ .execute()
836
+
837
  if not quiz_res.data:
838
  return jsonify({'error': 'Quiz not found'}), 404
 
 
 
839
 
840
+ quiz_questions = quiz_res.data['questions']
841
+ if isinstance(quiz_questions, str):
842
+ quiz_questions = json.loads(quiz_questions)
843
 
844
+ # Calculate Score
845
  correct_count = 0
846
  total_questions = len(quiz_questions)
847
+ feedback = {}
848
+ correct_answers = {}
849
+
850
+ for i, question in enumerate(quiz_questions):
851
+ question_id = question.get('id', str(i)) # Use question.id if exists, otherwise index
852
+ user_answer = user_answers.get(str(question_id)) # Match by question_id
853
+ correct_answer = question.get('correct_answer')
854
+
855
+ if user_answer and correct_answer:
856
+ is_correct = user_answer.upper() == correct_answer.upper()
857
+ if is_correct:
858
+ correct_count += 1
859
+
860
+ correct_answers[str(question_id)] = correct_answer
861
+ feedback[str(question_id)] = {
862
+ "correct": is_correct,
863
+ "correct_answer": correct_answer,
864
+ "user_answer": user_answer
865
+ }
866
 
867
  score = (correct_count / total_questions) * 100 if total_questions > 0 else 0.0
868
 
869
+ # Save Quiz Attempt
870
  attempt_res = supabase.table('quiz_attempts').insert({
871
  'quiz_id': str(quiz_id),
872
  'user_id': user.id,
873
  'score': score,
874
+ 'answers': json.dumps(user_answers)
875
  }).execute()
 
 
876
 
877
  return jsonify({
878
  'success': True,
879
+ 'attempt_id': attempt_res.data[0]['id'],
880
  'score': round(score, 2),
881
  'correct_count': correct_count,
882
  'total_questions': total_questions,
883
+ 'correct_answers': correct_answers, # Send back correct answers
884
+ 'feedback': feedback
885
  }), 201
886
 
 
 
887
  except Exception as e:
888
+ logging.error(f"Error submitting quiz: {traceback.format_exc()}")
889
+ return jsonify({'error': str(e)}), 500
890
 
891
 
892