📖 Scenario: You are building a simple Flask web app that counts how many times a user has visited the homepage during their session.
🎯 Goal: Create a Flask app that uses the session object to store and update a visit count for each user session. Display the visit count on the homepage.
📋 What You'll Learn
Create a Flask app with a homepage route
Use the Flask session object to store a visit count
Initialize the visit count if it does not exist
Increment the visit count on each visit
Display the current visit count on the homepage
💡 Why This Matters
🌍 Real World
Tracking user visits or preferences during a browsing session is common in web apps to personalize experience.
💼 Career
Understanding Flask sessions is essential for backend web development roles using Python and Flask framework.
Progress0 / 4 steps
1
Set up Flask app and secret key
Write code to import Flask and session from flask. Create a Flask app called app and set app.secret_key to the string 'mysecret'.
Flask
Hint
The secret_key is needed to use sessions in Flask.
2
Create homepage route and initialize visit count
Add a route for '/' using @app.route. Define a function called index. Inside it, check if 'visits' is not in session. If not, set session['visits'] = 0.
Flask
Hint
Use @app.route('/') to create the homepage route.
3
Increment visit count on each visit
Inside the index function, after initializing session['visits'], add 1 to session['visits'] to count the current visit.
Flask
Hint
Use session['visits'] += 1 to add one to the count.
4
Return visit count in response
At the end of the index function, return a string that says "You have visited this page X times." where X is the current value of session['visits']. Use an f-string to insert the number.
Flask
Hint
Use return f"You have visited this page {session['visits']} times." to show the count.
Practice
(1/5)
1. What is the main purpose of the Flask session object?
easy
A. To store user-specific data temporarily between requests
B. To connect to a database
C. To handle file uploads
D. To render HTML templates
Solution
Step 1: Understand the role of session in Flask
The session object is designed to keep data for a user during their visit, like a temporary storage.
Step 2: Compare with other options
Connecting to databases, handling uploads, and rendering templates are done by other Flask features, not session.
Final Answer:
To store user-specific data temporarily between requests -> Option A
Quick Check:
Session stores user data temporarily [OK]
Hint: Session stores data per user visit like a temporary box [OK]
Common Mistakes:
Thinking session connects to databases
Confusing session with template rendering
Assuming session handles file uploads
2. Which of the following is the correct way to import and use the Flask session object?
easy
A. import flask.session
flask.session['user'] = 'Alice'
B. from flask_session import Session
Session['user'] = 'Alice'
C. from flask import session
session['user'] = 'Alice'
D. import session
session['user'] = 'Alice'
Solution
Step 1: Check the correct import statement
The Flask session object is imported directly from flask using from flask import session.
Step 2: Verify usage syntax
After import, you can use it like a dictionary: session['user'] = 'Alice'.
Final Answer:
from flask import session\nsession['user'] = 'Alice' -> Option C
Quick Check:
Import session from flask and assign like dict [OK]
Hint: Import session directly from flask, then use like a dict [OK]
Common Mistakes:
Trying to import session from flask_session package
Using wrong import syntax like import session
Accessing session as flask.session instead of from flask import session
3. What will be the output of this Flask route code snippet?
Flask sessions require app.secret_key to encrypt session data securely.
Step 2: Identify missing secret_key
The code does not set app.secret_key, so session will raise an error or not work properly.
Final Answer:
Missing app.secret_key causing session error -> Option B
Quick Check:
Secret key missing breaks session [OK]
Hint: Always set app.secret_key before using session [OK]
Common Mistakes:
Forgetting to set secret_key
Assuming session works without secret_key
Misreading import or decorator syntax
5. You want to store a user's preferred language in the Flask session and ensure it persists across requests. Which code snippet correctly sets and retrieves this value safely?
hard
A. session['lang'] = 'en'
lang = session['language']
B. session['lang'] = 'en'
lang = session['lang']
C. session.set('lang', 'en')
lang = session.get('lang')
D. session['lang'] = 'en'
lang = session.get('lang', 'default')
Solution
Step 1: Set session value correctly
Assigning with session['lang'] = 'en' is correct to store the language.
Step 2: Retrieve session value safely
Using session.get('lang', 'default') safely gets the value or returns 'default' if missing, avoiding errors.
Final Answer:
session['lang'] = 'en'\nlang = session.get('lang', 'default') -> Option D
Quick Check:
Use session.get() to avoid KeyError [OK]
Hint: Use session.get() to safely read session keys [OK]
Common Mistakes:
Using session.set() which does not exist
Accessing wrong key causing KeyError
Not providing default value when reading session
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.