0
0
Flaskframework~30 mins

Session lifetime in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Managing Session Lifetime in Flask
📖 Scenario: You are building a simple Flask web app that tracks user visits using sessions. You want to control how long the session lasts before it expires automatically.
🎯 Goal: Create a Flask app that sets a session lifetime of 5 minutes and stores a visit count in the session. The app should increment the count on each visit and reset after the session expires.
📋 What You'll Learn
Create a Flask app with session support
Set the session lifetime to 5 minutes
Store a visit count in the session
Increment the visit count on each page load
Ensure the session expires after 5 minutes of inactivity
💡 Why This Matters
🌍 Real World
Web apps often need to remember user data temporarily, like login status or preferences. Managing session lifetime helps improve security and user experience by controlling how long this data stays active.
💼 Career
Understanding session management is essential for backend web developers working with Flask or similar frameworks to build secure and user-friendly applications.
Progress0 / 4 steps
1
Set up Flask app and secret key
Create a Flask app instance called app and set app.secret_key to the string 'mysecret'.
Flask
Need a hint?

The secret key is needed to use sessions securely in Flask.

2
Configure session lifetime
Import timedelta from datetime and set app.permanent_session_lifetime to timedelta(minutes=5).
Flask
Need a hint?

Use timedelta to specify the session lifetime duration.

3
Create route to track visits with session
Import session and redirect, url_for from flask. Create a route / with a function index() that sets session.permanent = True, increments session['visits'] by 1 (initialize to 1 if not present), and returns the visit count as a string.
Flask
Need a hint?

Mark the session as permanent to apply the lifetime. Use session like a dictionary to store visit counts.

4
Run the Flask app
Add the code to run the Flask app with app.run(debug=True) inside the if __name__ == '__main__': block.
Flask
Need a hint?

This code starts the Flask server so you can test your app in a browser.