Welcome, aspiring developers! Have you ever wanted to create your own interactive web application? Flask, a lightweight Python web framework, is a fantastic starting point. It’s simple, flexible, and perfect for building small to medium-sized projects, like the quiz app we’re going to build today!
This guide will walk you through creating a simple quiz application using Flask. By the end, you’ll have a working web app where users can answer questions and see their score. Let’s get started on this fun journey!
What is Flask?
Before we dive into coding, let’s briefly understand what Flask is.
Flask is a “micro” web framework written in Python.
* Web Framework: Think of it as a toolkit that provides structure and tools to build web applications more easily. Instead of writing every single piece of code from scratch (like handling web requests, managing templates, etc.), a framework gives you a head start.
* Micro: This means Flask aims to keep the core simple but allows you to add features and extensions as your project grows. It doesn’t force you into specific ways of doing things, giving you a lot of freedom.
Why Flask for a quiz app? It’s perfect for beginners because it has a gentle learning curve, letting us focus on the core logic of our quiz without getting bogged down by too many complexities.
What You’ll Need
To follow along, you’ll need a few things:
- Python: Make sure you have Python installed on your computer (version 3.6 or higher is recommended). You can download it from the official Python website.
- A Text Editor: Any code editor like VS Code, Sublime Text, or even Notepad++ will work.
- Basic Command Line Knowledge: Knowing how to navigate folders and run commands in your terminal or command prompt will be helpful.
That’s it! We’ll install Flask together.
Step 1: Set Up Your Project
First, let’s create a dedicated folder for our project and set up a virtual environment.
What’s a Virtual Environment?
A virtual environment is like a self-contained box for your Python project. It allows you to install specific Python libraries (like Flask) for one project without interfering with other projects or your system’s global Python installation. It’s a best practice for managing dependencies!
-
Create a Project Directory:
Open your terminal or command prompt and create a new folder:bash
mkdir flask_quiz_app
cd flask_quiz_app -
Create a Virtual Environment:
Inside yourflask_quiz_appfolder, run this command:bash
python -m venv venv
This creates a new folder namedvenvinside your project, which contains your virtual environment. -
Activate the Virtual Environment:
Now, let’s step into our virtual environment:- On Windows:
bash
.\venv\Scripts\activate - On macOS/Linux:
bash
source venv/bin/activate
You’ll know it’s activated when you see(venv)at the beginning of your command prompt.
- On Windows:
-
Install Flask:
With your virtual environment active, install Flask usingpip(Python’s package installer):bash
pip install Flask
pipwill download and install Flask and its necessary components into yourvenv.
Step 2: Build the Core Flask App (app.py)
Now, let’s start writing our Flask application. Create a new file named app.py inside your flask_quiz_app folder.
This file will contain all the logic for our quiz.
Basic Flask Structure
Let’s start with a very basic Flask app to make sure everything is working.
from flask import Flask
app = Flask(__name__) # Creates a Flask application instance
@app.route('/') # This is a "route" - it tells Flask what to do when someone visits the '/' URL (homepage)
def home():
return "Hello, Quiz Master!" # What to show on the homepage
if __name__ == '__main__':
app.run(debug=True) # Runs the Flask development server. debug=True allows for auto-reloading and helpful error messages.
Explanation of terms:
* from flask import Flask: We import the Flask class from the flask library. This is the main building block for our app.
* app = Flask(__name__): We create an instance of the Flask class. __name__ helps Flask find resources like templates and static files.
* @app.route('/'): This is a decorator. It tells Flask that the home function should be executed when a user visits the root URL (/) of our application.
* def home():: This is a view function. It’s responsible for handling requests to a specific route and returning a response.
* app.run(debug=True): This command starts the Flask development server. When debug=True, the server will automatically restart whenever you make changes to your code, and it will provide detailed error messages in your browser, which is super helpful during development.
Running Your First Flask App
- Save your
app.pyfile. - Go back to your terminal (make sure your virtual environment is still active).
-
Run your app:
bash
python app.py
You should see output similar to this:
* Serving Flask app 'app'
* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on http://127.0.0.1:5000
Press CTRL+C to quit
4. Open your web browser and go tohttp://127.0.0.1:5000. You should see “Hello, Quiz Master!”.
Congratulations, your Flask app is running! Press CTRL+C in your terminal to stop the server for now.
Step 3: Define Your Quiz Questions
Our quiz needs questions! Let’s store them in a Python list of dictionaries. Each dictionary will represent a question with its text, options, and the correct answer.
Add this code to your app.py file, ideally at the top, just after app = Flask(__name__).
app.secret_key = 'your_super_secret_key' # Needed for Flask sessions (explained later)
QUESTIONS = [
{
'id': 0,
'question': "What is the capital of France?",
'options': ["London", "Berlin", "Paris", "Rome"],
'answer': "Paris"
},
{
'id': 1,
'question': "Which planet is known as the Red Planet?",
'options': ["Earth", "Mars", "Jupiter", "Venus"],
'answer': "Mars"
},
{
'id': 2,
'question': "What is the largest ocean on Earth?",
'options': ["Atlantic", "Indian", "Arctic", "Pacific"],
'answer': "Pacific"
}
]
app.secret_key explanation:
Flask uses something called “sessions” to remember information about a user as they navigate your app (like their score or current question). To keep this information secure, Flask needs a secret_key. For development, a simple string is fine, but for a real-world app, you’d want a much more complex and randomly generated key.
Step 4: Create HTML Templates
Instead of just returning “Hello, Quiz Master!”, we want to display proper web pages. Flask uses templates for this, which are HTML files with special placeholders for dynamic content.
Create a new folder named templates inside your flask_quiz_app directory. This is where Flask will look for your HTML files.
templates/index.html (Quiz Start Page)
This will be our landing page where users can start the quiz.
Create templates/index.html:
<!-- templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flask Quiz App</title>
<style>
body { font-family: sans-serif; margin: 40px; background-color: #f4f4f4; color: #333; }
.container { max-width: 600px; margin: auto; padding: 20px; background: white; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
h1 { color: #0056b3; }
.button {
display: inline-block;
padding: 10px 20px;
margin-top: 20px;
background-color: #007bff;
color: white;
text-decoration: none;
border-radius: 5px;
transition: background-color 0.3s ease;
}
.button:hover { background-color: #0056b3; }
</style>
</head>
<body>
<div class="container">
<h1>Welcome to the Flask Quiz!</h1>
<p>Test your knowledge with these fun questions.</p>
<a href="/question/0" class="button">Start Quiz</a>
</div>
</body>
</html>
templates/question.html (Display a Question)
This template will show one question at a time and allow the user to select an answer.
Create templates/question.html:
<!-- templates/question.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Question {{ question['id'] + 1 }}</title>
<style>
body { font-family: sans-serif; margin: 40px; background-color: #f4f4f4; color: #333; }
.container { max-width: 600px; margin: auto; padding: 20px; background: white; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
h2 { color: #0056b3; }
ul { list-style: none; padding: 0; }
li { margin-bottom: 10px; }
input[type="radio"] { margin-right: 10px; }
.button {
padding: 10px 20px;
margin-top: 20px;
background-color: #28a745;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
}
.button:hover { background-color: #218838; }
</style>
</head>
<body>
<div class="container">
<h2>Question {{ question['id'] + 1 }} of {{ total_questions }}</h2>
<p>{{ question['question'] }}</p>
<form action="/submit_answer" method="post">
<ul>
{% for option in question['options'] %}
<li>
<input type="radio" id="option_{{ loop.index }}" name="answer" value="{{ option }}" required>
<label for="option_{{ loop.index }}">{{ option }}</label>
</li>
{% endfor %}
</ul>
<input type="hidden" name="question_id" value="{{ question['id'] }}">
<button type="submit" class="button">Submit Answer</button>
</form>
</div>
</body>
</html>
Jinja2 Templating:
Notice the {{ ... }} and {% ... %} in the HTML files? This is Jinja2, the templating engine Flask uses.
* {{ variable }}: This is used to display the value of a Python variable passed to the template.
* {% for item in list %} and {% endfor %}: These are control structures, similar to Python’s for loops, used to iterate over data.
* {{ loop.index }}: A special variable available inside a for loop that gives you the current iteration count (useful for unique IDs).
templates/results.html (Show Quiz Results)
Finally, a page to display the user’s score.
Create templates/results.html:
<!-- templates/results.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Quiz Results</title>
<style>
body { font-family: sans-serif; margin: 40px; background-color: #f4f4f4; color: #333; }
.container { max-width: 600px; margin: auto; padding: 20px; background: white; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
h1 { color: #0056b3; }
.score { font-size: 2em; color: #28a745; font-weight: bold; }
.button {
display: inline-block;
padding: 10px 20px;
margin-top: 20px;
background-color: #007bff;
color: white;
text-decoration: none;
border-radius: 5px;
transition: background-color 0.3s ease;
}
.button:hover { background-color: #0056b3; }
</style>
</head>
<body>
<div class="container">
<h1>Quiz Complete!</h1>
<p>You scored: <span class="score">{{ score }} / {{ total_questions }}</span></p>
<a href="/" class="button">Play Again</a>
</div>
</body>
</html>
Step 5: Update app.py with Quiz Logic
Now we connect our questions and templates by updating app.py. We’ll need to use session to store the user’s score and current question index, render_template to display our HTML, and request to get data from forms.
Add these imports at the top of your app.py:
from flask import Flask, render_template, request, redirect, url_for, session
Then, replace or add these routes and functions:
@app.route('/')
def home():
session['score'] = 0 # Reset score when starting the quiz
session['current_question_index'] = 0 # Start from the first question
return render_template('index.html')
@app.route('/question/<int:question_id>')
def show_question(question_id):
if question_id >= len(QUESTIONS):
# If no more questions, go to results
return redirect(url_for('show_results'))
# Check if the user is trying to skip questions
if question_id != session.get('current_question_index', 0):
# Redirect them to the correct question if they try to cheat by changing URL
return redirect(url_for('show_question', question_id=session['current_question_index']))
question = QUESTIONS[question_id]
return render_template('question.html',
question=question,
total_questions=len(QUESTIONS))
@app.route('/submit_answer', methods=['POST'])
def submit_answer():
question_id = int(request.form['question_id'])
user_answer = request.form['answer']
current_question = QUESTIONS[question_id]
if user_answer == current_question['answer']:
session['score'] += 1 # Increment score if correct
session['current_question_index'] += 1 # Move to the next question
# Check if there are more questions
if session['current_question_index'] < len(QUESTIONS):
return redirect(url_for('show_question', question_id=session['current_question_index']))
else:
return redirect(url_for('show_results'))
@app.route('/results')
def show_results():
final_score = session.get('score', 0)
total = len(QUESTIONS)
return render_template('results.html', score=final_score, total_questions=total)
if __name__ == '__main__':
app.run(debug=True)
New Flask Functions/Concepts:
* render_template('filename.html', var1=value1): This function tells Flask to load an HTML file from the templates folder and pass Python variables to it.
* request.form: When a form is submitted with method="post", Flask makes the form data available in request.form. You can access values by their name attribute from the HTML input fields (e.g., request.form['answer']).
* redirect(url_for('function_name', keyword=value)): redirect sends the user’s browser to a different URL. url_for helps generate the correct URL for a given Flask view function, even if the URL pattern changes.
* session: This is a special dictionary-like object provided by Flask to store user-specific data that persists across different requests. It’s stored securely on the client-side (in a cookie) and signed with app.secret_key. We use it here to keep track of the user’s score and current_question_index.
Step 6: Run Your Quiz App!
- Save all your files.
- Make sure your virtual environment is active.
-
Run the Flask app from your terminal:
bash
python app.py
4. Open your browser tohttp://127.0.0.1:5000.
You should now see the “Welcome to the Flask Quiz!” page. Click “Start Quiz,” answer the questions, and see your final score!
Conclusion and Next Steps
Congratulations! You’ve successfully built a basic quiz application using Flask. You’ve learned how to:
- Set up a Flask project with a virtual environment.
- Define routes to handle different URLs.
- Use HTML templates to render dynamic web pages.
- Handle form submissions.
- Manage user-specific data using Flask
session.
This is just the beginning! Here are some ideas for how you can expand your quiz app:
- Add more questions!
- Improve styling: Use a dedicated CSS file (in a
staticfolder) for better design. - Feedback: Show if an answer was correct or incorrect after submission.
- Timer: Add a time limit for each question or the entire quiz.
- Different quiz categories: Allow users to choose a topic.
- User accounts: Store scores in a database.
Flask is incredibly versatile, and this project demonstrates its power in creating interactive web experiences with Python. Keep experimenting, and happy coding!
Leave a Reply
You must be logged in to post a comment.