from flask import Flask, render_template, request, redirect, url_for, session from flask_session import Session import json import random import os 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['name'] = request.form['name'] session['questions'] = [] session['answers'] = [] session['score'] = 0 session['current_question'] = 0 selected_file = request.form['file'] session['selected_file'] = selected_file 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': answer = request.form.get('answer') if answer: session['answers'].append(answer) if answer in session['questions'][session['current_question']]['correct']: 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')) return render_template('quiz.html', question=session['questions'][session['current_question']], question_number=session['current_question'] + 1, total_questions=len(session['questions']), selected_file=session['selected_file']) @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 return render_template('results.html', name=session['name'], score=session['score'], total_questions=total_questions, score_percentage=score_percentage) if __name__ == '__main__': app.run(host='0.0.0.0', port=7860)