0
0
Flaskframework~5 mins

Session lifetime in Flask

Choose your learning style9 modes available
Introduction

Session lifetime controls how long a user's session stays active before it expires. This helps keep user data safe and improves app behavior.

You want users to stay logged in for a certain time after they close the browser.
You want to automatically log out users after inactivity for security.
You want to control how long shopping cart data stays in a session.
You want to customize session expiration based on user roles or actions.
Syntax
Flask
from flask import Flask, session
from datetime import timedelta

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

# Set session lifetime
app.permanent_session_lifetime = timedelta(minutes=30)

@app.route('/')
def index():
    session.permanent = True  # Make session permanent to use lifetime
    session['user'] = 'Alice'
    return 'Session is set with 30 minutes lifetime'

Use app.permanent_session_lifetime to set how long sessions last.

Set session.permanent = True inside a route to apply the lifetime to that session.

Examples
Set session to last 1 hour.
Flask
app.permanent_session_lifetime = timedelta(hours=1)
session.permanent = True
Set session to last 7 days for a 'remember me' feature.
Flask
app.permanent_session_lifetime = timedelta(days=7)
session.permanent = True
Session will expire when the browser closes (default behavior).
Flask
session.permanent = False
Sample Program

This Flask app sets a session lifetime of 10 seconds. When you visit '/', it starts a session for user 'Bob'. Visiting '/check' shows the current session user or says no active session if expired.

Flask
from flask import Flask, session
from datetime import timedelta

app = Flask(__name__)
app.secret_key = 'secret123'
app.permanent_session_lifetime = timedelta(seconds=10)

@app.route('/')
def index():
    session.permanent = True
    session['username'] = 'Bob'
    return 'Session started for Bob with 10 seconds lifetime.'

@app.route('/check')
def check():
    user = session.get('username', 'No active session')
    return f'Current session user: {user}'

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Sessions with permanent = False expire when the browser closes.

Make sure to set a secret_key for sessions to work securely.

Session lifetime helps balance user convenience and security.

Summary

Session lifetime controls how long user data stays in a session.

Set app.permanent_session_lifetime to define duration.

Use session.permanent = True to apply the lifetime.