0
0
Flaskframework~30 mins

Flask session object - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Flask session object to track user visits
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use return f"You have visited this page {session['visits']} times." to show the count.