Sessions: Managing user state in Flask.

Derrick Sekidde
Crane Cloud
Published in
3 min readAug 18, 2023

--

Photo by Lucas van Oort on Unsplash

In today’s digital landscape, captivating user engagement and providing tailored experiences is paramount for the success of any tech tool or application. Imagine seamlessly remembering user preferences, and maintaining shopping carts across visits. How do your favorite applications and sites do it?

Enter Sessions — let us uncover its inner workings, and equip you with the knowledge to transform the way you approach user state management. Sessions enable you to maintain user-specific data across multiple requests and Flask provides a simple solution for handling sessions.

Sessions allow web applications to store and retrieve user-specific information, such as login credentials, preferences, and shopping cart contents, across multiple HTTP requests. In utilizing sessions, we can create personalized experiences for users and maintain continuity throughout their interactions with the application.

A session is encrypted information that is stored on the web server in a temporary directory. Encrypting data is a secure method employed to store information, particularly when the data should remain untouched or hidden from the user’s view.

Enable Sessions in Flask:

Flask provides a built-in session management system that relies on signed cookies to store and retrieve session data securely. To illustrate how we can use sessions let us experiment with a simple example.

from flask import Flask, session
import secrets

app = Flask(__name__)
app.secret_key = 'my_hard_to_crack_secret_key'
# below is how i run mine
# app.secret_key = secrets.token_hex(16)

In the above code, we import the session from the flask module first. The app.secret_key is used to sign the session cookie, to add an extra layer of security that’s why we can’t run sessions without it. Personally, for extra security, I use ‘secrets’ to help me with that.

Storing our first Session:

Sessions are key-value pairs or essentially python dictionaries as such adding information can be easy as:

session["key"] = "value"

Most sessions are created at login and let’s explore how to do that:

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

app = Flask(__name__)
app.secret_key = secrets.token_hex(16)

@app.route('/login', methods=[ 'POST'])
def login():
if request.method == 'POST':
username = request.form.get('username')
# Assuming successful authentication
session['username'] = username
session['token'] = access_token
session['role'] = user.role
session["user"] = user
return redirect(url_for('profile'))

Information retrieval from a session.

@app.route('/profile')
def profile():
if "user" in session:
user = session["user"]
return f"<h1>{user}</h1>"
else:
return redirect(url_for("login"))

And in our profile page, we can check the session if the user exists and if so we can display user data.

@app.route('/profile')
def profile():
access_token = session.get('user_token')
role = session.get('user_role')
username = session.get('username')
return render_template('profile.html', token=access_token, role=role, user=username)

and in the profile page we can use can pick the stored user details as shown below:

<nav class="header-user-info">
<div id="username">{{ session.username }}</div>
<div id="user_role">{{ session.role }}</div>
</div>

Clearing the sessions:

Now, let’s proceed to implement the session clearing, this is usually done with the logout functionality. When a user navigates to “/logout” route, it’s essential to erase their session information. To accomplish this, we can employ a technique known as session.pop(“key”, None). The pop method attempts to eliminate and retrieve the specified key from the session data. If the key is not present, the method will return the provided second argument. In our scenario, we aim to eliminate the “user” key, and if it’s not found, we’ll return None.

@app.route("/logout")
def logout():
session.pop("username", None)
session.pop("token", None)
session.pop("role", None)
session.pop("user", None)
return redirect(url_for("login"))

How long is a Session?

Now that we are familiar with the process of establishing, adding, and eliminating data within sessions, it’s time to delve into their lifespan. By default, a session remains active for the duration of your browser being open. Nonetheless, Flask provides a means to adjust this behavior. We can influence the session’s duration by creating a permanent session, affording us the ability to stipulate its longevity. By default, a permanent session lasts for 30 days. We will start by defining the duration at the beginning of our program.

app.permanent_session_lifetime = timedelta(days=1)

As shown above I have set the session duration for a day and incase of its expiry I have the login redirect functionality where a user will get redirected to the login to start a new session. That is all about sessions, if I missed out anything or you have a question add a comment. Happy coding.

--

--