A quiz system presents questions, captures selected answers, stores responses, and advances until the quiz reaches completion. A practical Flask version separates the interface, request routes, question retrieval, answer storage, and results display. section 7.1 section 7.1.3
A minimal implementation needs these cooperating pieces:
- Retrieve one question from the database and pass it to a Flask template. section 7.1.1
- Render the question and possible answers as a form with selectable options. section 7.1.1 section 7.1.3
- Capture the submission, store the selected answer, and redirect to the next question. section 7.1 section 7.1.3
- End the sequence with a completion or results page, while validating missing selections and database failures. section 7.1.1 section 7.1.3
A small Flask quiz flow
A SQLite database contains 35 questions. The quiz route loads a question by identifier, displays four radio-button answers, accepts a POST submission, stores the response, and redirects to the next identifier. After the final question, it redirects to a results template. Keep the generated design under review: one proposal introduced SQLAlchemy even though a direct SQLite approach was preferred. section 7.1 section 7.1.3
from flask import Flask, render_template, request, redirect, url_for
from quiz_db import get_questions, store_answer
app = Flask(__name__)
@app.route('/')
def index():
return redirect(url_for('quiz'))
@app.route('/quiz', methods=['GET', 'POST'])
def quiz():
question_id = request.args.get('question_id', 1)
question = get_questions(question_id)
if request.method == 'POST':
selected_answer = request.form['answer']
store_answer(question_id, selected_answer)
if question_id < 35:
return redirect(url_for('quiz', question_id=question_id + 1))
else:
return redirect(url_for('results'))
return render_template('quiz.html', question=question)
@app.route('/results')
def results():
return render_template('results.html')
if __name__ == '__main__':
app.run(debug=True)
Inspect the compact Flask route implementation showing question selection, POST handling, answer storage, progression, and results navigation. section 7.1.3
