0
0
FlaskHow-ToBeginner · 4 min read

How to Use Session in Flask: Simple Guide with Examples

In Flask, you use the session object to store data across requests for a user. You must set a SECRET_KEY in your app to securely sign the session cookie. Use session['key'] = value to save data and session.get('key') to retrieve it.
📐

Syntax

The session object in Flask works like a dictionary to store user-specific data. You assign values with session['key'] = value and read them with session.get('key'). To use sessions, you must set app.secret_key to a secret string for security.

  • app.secret_key: A secret string to sign session cookies.
  • session['key'] = value: Store data in the session.
  • session.get('key'): Retrieve data safely from the session.
  • session.pop('key'): Remove data from the session.
python
from flask import Flask, session

app = Flask(__name__)
app.secret_key = 'your_secret_key_here'  # Must be secret and random

@app.route('/set')
def set_session():
    session['username'] = 'Alice'
    return 'Session data set!'

@app.route('/get')
def get_session():
    user = session.get('username', 'Not logged in')
    return f'Hello, {user}!'

@app.route('/clear')
def clear_session():
    session.pop('username', None)
    return 'Session cleared!'
💻

Example

This example shows a simple Flask app that sets a username in the session, retrieves it, and clears it. It demonstrates how session data persists across requests for the same user.

python
from flask import Flask, session

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

@app.route('/login')
def login():
    session['user'] = 'Bob'
    return 'User logged in and session set.'

@app.route('/profile')
def profile():
    user = session.get('user')
    if user:
        return f'Welcome back, {user}!'
    else:
        return 'You are not logged in.'

@app.route('/logout')
def logout():
    session.pop('user', None)
    return 'User logged out and session cleared.'

if __name__ == '__main__':
    app.run(debug=True)
Output
Running the app and visiting /login sets the session. Visiting /profile shows 'Welcome back, Bob!'. Visiting /logout clears the session. Visiting /profile again shows 'You are not logged in.'
⚠️

Common Pitfalls

  • Not setting app.secret_key causes sessions to not work or raise errors.
  • Storing large or sensitive data in sessions is not recommended because session data is stored client-side in cookies.
  • Forgetting to use session.get('key') can cause errors if the key does not exist.
  • Modifying session data without committing changes (like forgetting to assign) will not persist data.
python
from flask import Flask, session

app = Flask(__name__)
# app.secret_key is missing here - session will not work properly

@app.route('/set')
def set_session():
    session['data'] = 'value'  # This will raise an error or not persist
    return 'Set session data'

# Correct way:
app.secret_key = 'a_secure_random_key'

@app.route('/set_correct')
def set_session_correct():
    session['data'] = 'value'
    return 'Session data set correctly'
📊

Quick Reference

Remember these key points when using Flask sessions:

  • Always set app.secret_key before using sessions.
  • Use session['key'] = value to store data.
  • Use session.get('key') to safely retrieve data.
  • Use session.pop('key', None) to remove data.
  • Keep session data small and non-sensitive.

Key Takeaways

Set a secret key with app.secret_key to enable secure sessions.
Use session like a dictionary to store and retrieve user data across requests.
Avoid storing large or sensitive data in sessions as they are stored client-side.
Always use session.get() to avoid errors when keys are missing.
Clear session data with session.pop() when no longer needed.