Introduction to sessions
A session is used to store information related to a user, across different requests, as they interact with a web app. The data stored for a session should be considered temporary data, as the session will eventually expire. In order to permanently store date, you need to utilise a database.
Flask uses the client-side approach where sessions are stored in browser cookies. This cookie is sent with each request to the Flask app on the server-side where it's decoded.
Pros:
Validating and creating sessions is fast (no data storage)
Easy to scale (no need to replicate session data across web servers)
Cons:
Sensitive data cannot be stored in session data, as it's stored on the web browser
Session data is limited by the size of the cookie (usually 4 KB)
Sessions cannot be immediately revoked by the Flask app
from flask import Flask, request, redirect, session
app = Flask(__name__)
# SECRET_KEY is required to encrypt the contents of the session
app.config['SECRET_KEY'] = 'This is a pretend secret key.'
@app.route('/')
def home():
# Access sessions values
# Can also use `session['pet_name']` but it fails if the key isn't there.
pet_name = session.get('pet_name', '')
if pet_name:
return f'<h1>Your pet\'s name is {pet_name}.</h1>'
else:
return f'<h1>I do not know your pet\'s name.</h1> <a href="/petname">set pet name</a>'
@app.route('/petname')
def pet_name():
return f'<form method="POST"><input type="text" name="pet"><input type="submit"></form>'
@app.route('/petname', methods=['POST'])
def pet_name_action():
pet_name = request.form.get('pet')
# Set the session value
session['pet_name'] = pet_name
return redirect('/')
app.run(debug=True)
Session Life
By default, the session
object remains in place until the browser is closed. However, if you want to change the life of the session
object, define the PERMANENT_SESSION_LIFETIME configuration variable after creating the Flask app
:
import datetime
# session cookie is valid for 1 minute after the browser is closed
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(minutes=1)
When setting the data in the session
, specify that the sessions should be permanent (time will be based on PERMANENT_SESSION_LIFETIME
):
# Save the form data to the session object
session['email'] = request.form['email_address']
session.permanent = True
References
Last updated
Was this helpful?