0
0
FlaskHow-ToBeginner · 4 min read

How to Implement Session in Flask: Simple Guide with Example

In Flask, you implement session management using the built-in session object, which stores data on the client securely with cookies. You must set a SECRET_KEY in your app to encrypt session data and then read or write session variables like a dictionary.
📐

Syntax

The session object in Flask works like a dictionary to store user-specific data across requests. You set a SECRET_KEY in your Flask app to encrypt session cookies securely. Use session['key'] = value to save data and session.get('key') to retrieve it.

python
from flask import Flask, session

app = Flask(__name__)
app.secret_key = 'your_secret_key_here'  # Needed to encrypt session data

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

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

Example

This example shows a simple Flask app that sets a username in the session and then retrieves it on another page. It demonstrates how session data persists between requests for the same user.

python
from flask import Flask, session

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

@app.route('/login')
def login():
    session['username'] = 'Alice'
    return 'Logged in as Alice'

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

if __name__ == '__main__':
    app.run(debug=True)
Output
When you visit /login, it shows: Logged in as Alice When you visit /profile after that, it shows: Welcome back, Alice!
⚠️

Common Pitfalls

  • Not setting app.secret_key causes sessions to fail silently or be insecure.
  • Storing large or sensitive data in sessions is not recommended because data is stored client-side in cookies.
  • Forgetting to check if a session key exists before accessing it can cause errors.
  • Sessions are cookie-based, so users can clear cookies and lose session data.
python
from flask import Flask, session

app = Flask(__name__)
# Missing secret_key causes session to not work properly

@app.route('/set')
def set():
    session['data'] = 'value'
    return 'Set data'

@app.route('/get')
def get():
    # Wrong: directly accessing session['data'] without checking
    # This can raise KeyError if 'data' not set
    value = session.get('data', 'No data found')
    return f'Data: {value}'
📊

Quick Reference

Session Management Cheat Sheet:

  • Set secret key: app.secret_key = 'your_secret'
  • Save data: session['key'] = value
  • Read data safely: session.get('key')
  • Remove data: session.pop('key', None)
  • Clear all session data: session.clear()

Key Takeaways

Always set a strong secret key with app.secret_key to secure session data.
Use the session object like a dictionary to store and retrieve user data.
Avoid storing sensitive or large data in sessions because data is stored client-side.
Check if session keys exist before accessing to prevent errors.
Sessions rely on cookies, so users can lose session data by clearing cookies.