Fausto Busuito
Application changes
4556c83
raw
history blame
2.34 kB
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']
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':
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'))
return render_template('quiz.html', question=session['questions'][session['current_question']],
question_number=session['current_question'] + 1,
total_questions=len(session['questions']))
@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)