from flask import Flask, render_template, request, redirect, url_for, session from flask_session import Session import json import random import os import time app = Flask(__name__) app.secret_key = 'supersecretkey' # Configure Flask-Session app.config['SESSION_TYPE'] = 'filesystem' Session(app) QUESTIONS_FOLDER = 'questions' @app.route('/') def index(): files = [f for f in os.listdir(QUESTIONS_FOLDER) if f.endswith('.json')] return render_template('index.html', files=files) @app.route('/start', methods=['POST']) def start(): session['questions'] = [] session['answers'] = [] session['score'] = 0 session['current_question'] = 0 session['start_time'] = time.time() selected_file = request.form['file'] session['selected_file'] = os.path.splitext(selected_file)[0] # Remove file extension file_path = os.path.join(QUESTIONS_FOLDER, selected_file) with open(file_path, 'r') as file: questions = json.load(file) random.shuffle(questions) session['questions'] = questions return redirect(url_for('quiz')) @app.route('/quiz', methods=['GET', 'POST']) def quiz(): if 'questions' not in session or 'current_question' not in session: return redirect(url_for('index')) if request.method == 'POST': action = request.form.get('action') if action == 'next': answers = request.form.getlist('answer') if answers: session['answers'].append(answers) correct_answers = session['questions'][session['current_question']]['correct'] if set(answers) == set(correct_answers): session['score'] += 1 session['current_question'] += 1 if session['current_question'] >= len(session['questions']): return redirect(url_for('results')) elif action == 'previous': session['current_question'] -= 1 if session['current_question'] < 0: session['current_question'] = 0 elif action == 'end': return redirect(url_for('results')) question = session['questions'][session['current_question']] multiple_selection = 'SELECT TWO' in question['question'] or 'SELECT THREE' in question['question'] elapsed_time = time.time() - session['start_time'] elapsed_time_str = time.strftime('%H:%M:%S', time.gmtime(elapsed_time)) return render_template('quiz.html', question=question, question_number=session['current_question'] + 1, total_questions=len(session['questions']), selected_file=session['selected_file'], show_previous=session['current_question'] > 0, multiple_selection=multiple_selection, elapsed_time=elapsed_time_str) @app.route('/results') def results(): if 'questions' not in session or 'answers' not in session: return redirect(url_for('index')) total_questions = len(session['questions']) score_percentage = (session['score'] / total_questions) * 100 elapsed_time = time.time() - session['start_time'] elapsed_time_str = time.strftime('%H:%M:%S', time.gmtime(elapsed_time)) return render_template('results.html', score=session['score'], total_questions=total_questions, score_percentage=score_percentage, elapsed_time=elapsed_time_str) if __name__ == '__main__': app.run(host='0.0.0.0', port=7860)