0
0
Flaskframework~5 mins

Flask session object

Choose your learning style9 modes available
Introduction

The Flask session object lets you save small pieces of information about a user while they browse your website. It helps keep track of things like login status or preferences without needing a database.

Remember if a user is logged in during their visit.
Store user preferences like theme or language choice temporarily.
Keep track of items added to a shopping cart before checkout.
Save form data temporarily to refill fields if the user returns.
Count how many times a user has visited a page during a session.
Syntax
Flask
from flask import session

# Set a value
session['key'] = 'value'

# Get a value
value = session.get('key')

# Remove a value
session.pop('key', None)

The session object works like a dictionary to store key-value pairs.

Flask signs the session data to keep it secure but stores it on the client side by default.

Examples
Save the username 'alice' in the session.
Flask
session['username'] = 'alice'
Retrieve the username from the session safely.
Flask
user = session.get('username')
Remove the username from the session if it exists.
Flask
session.pop('username', None)
Sample Program

This simple Flask app uses the session object to remember if a user is logged in. When the user posts their username to /login, it saves it in the session. The index page shows if the user is logged in or not. The /logout route clears the session.

Flask
from flask import Flask, session, redirect, url_for, request

app = Flask(__name__)
app.secret_key = 'supersecretkey'

@app.route('/')
def index():
    if 'username' in session:
        return f"Logged in as {session['username']}"
    return 'You are not logged in'

@app.route('/login', methods=['POST'])
def login():
    username = request.form['username']
    session['username'] = username
    return redirect(url_for('index'))

@app.route('/logout')
def logout():
    session.pop('username', None)
    return redirect(url_for('index'))
OutputSuccess
Important Notes

Always set app.secret_key to keep session data secure.

Session data is stored client-side in cookies, so keep it small and avoid sensitive info.

Use session.get() to avoid errors if a key is missing.

Summary

The Flask session object stores user data temporarily during their visit.

It works like a dictionary and keeps data between requests.

Remember to set a secret key to protect session data.