0
0
Flaskframework~30 mins

Session data storage in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Session Data Storage with Flask
📖 Scenario: You are building a simple web app using Flask. You want to remember a user's name during their visit without asking every time. This is like remembering a friend's name when they come to your house.
🎯 Goal: Create a Flask app that stores a user's name in session data and shows it on the homepage.
📋 What You'll Learn
Create a Flask app instance
Set a secret key for sessions
Store a user's name in the session
Retrieve and display the stored name on the homepage
💡 Why This Matters
🌍 Real World
Web apps often need to remember users during their visit without asking repeatedly. Session data storage helps keep user info like login status or preferences.
💼 Career
Understanding session management is key for backend web developers to create personalized and secure user experiences.
Progress0 / 4 steps
1
Create Flask app and set secret key
Write code to import Flask and session from flask. Then create a Flask app instance called app. Finally, set the secret key of app to the string 'mysecretkey'.
Flask
Need a hint?

The secret key is needed to keep session data safe. Use app.secret_key = 'mysecretkey'.

2
Create a route to store the user's name in session
Add a route for /setname using @app.route('/setname'). Define a function called set_name that stores the string 'Alice' in the session under the key 'username'. Return the string 'Name stored in session.'.
Flask
Need a hint?

Use session['username'] = 'Alice' to save the name.

3
Create a homepage route to show the stored name
Add a route for / using @app.route('/') . Define a function called home that gets the 'username' from session using session.get('username'). Return a string f'Hello, {username}!' if the name exists, otherwise return 'Hello, Guest!'.
Flask
Need a hint?

Use session.get('username') to safely get the name.

4
Add the app run command to start the server
Add the code if __name__ == '__main__': and inside it call app.run(debug=True) to start the Flask server in debug mode.
Flask
Need a hint?

This code runs the app when you start the script.