You are currently viewing What are Sessions? How to use Sessions in Flask

What are Sessions? How to use Sessions in Flask

In this article, you’ll see what are sessions and how to utilize them in a Flask application to store information.

What are Sessions?

In general, a session is an active period of interaction between the user and the application. The entirety of the session is the time the user spends on an application from logging in to logging out.

Sessions can store and manage data across multiple requests. Sessions are particularly useful for managing user-related data and maintaining it between different interactions of a web application.

For instance, you can store the authentication status (whether the user is logged in or not) of the user on the server when the user logs in. Storing this information in a session allows the server to remember that the user is authenticated even as they navigate through different parts of the web application.

Using Sessions in a Flask App

To use sessions to store data on the server using the Flask app, you can use the flask module’s session.

Importing Required Modules

The session is imported from flask which will be used to access and manipulate session data in a Flask application.

The other functions and classes are imported from flask which will help in creating a Flask application and handling routes.

The timedelta class is imported from datetime module which will help in time-related tasks.

Setting Up Flask App

The Flask application is created by instantiating the Flask(__name__) and storing the instance in the app variable.

The secret key is set to "MY_SECRET_KEY" by calling the app object’s secret_key attribute. This will assist with session management.

Setting Up Session Timeout Duration

The session timeout is set to one minute (timedelta(minutes=1)) by calling the app object’s permanent_session_lifetime. After one minute, the active sessions will be terminated automatically.

Routes and View Functions

In this section, you will create routes and view functions for registering users, displaying relevant messages for the request, and storing them on the server via Flask session. You’ll then create a route and view function to remove the username from the session.

Home Route and View Function

This simple code defines the route ("/") and a view function called home that displays the home.html template.

Route and View Function for Registering Username

The "/add" route, which can handle both GET and POST requests, is defined in this code snippet.

The view function add_username() is defined, and it is in charge of displaying the add_username.html template. A message is stored in the session using session['message'] within the view function body.

The function then determines whether the request is a POST request and retrieves the value of "username" from the form. Using session['user'] = username, the retrieved username is saved in the session under the key 'user'.

After that, a message is saved in the session under the key 'greet' to notify users of their successful username registration, and the user is redirected to the home page.

Route and View Function for Removing Username

The code defines a "/remove" route and a remove_username view function.

Using session.pop('user'), the view function removes the username from the session. Following that, a message is saved under the key 'notify' to notify users that the username has been removed from the session and then they are redirected to the home page.

Creating Templates

You need to generate three HTML templates named base.html, home.html, and add_username.html within the templates directory.


This template includes an HTML skeleton as well as Bootstrap CSS and JavaScript.


In the above code snippet, the {% if not session['user'] %} block checks if there is no username and displays the message stored in the session under the key 'notify' otherwise displays the message stored in the session['greet'].

The {% if session['user'] %} block checks if there is a username, if there is, it displays the username with a “Log out” button otherwise displays the “Register” button to register the username.


This template includes a form with a username field and a “Submit” button to submit the username and save it in the session. At first, a message is displayed on the request to the "/add" URL, which is saved in the session under the key 'message'.


Here are some screenshots of testing the routes.

  1. Default or Home page preview.
Home page preview
  1. Adding the username and submitting the form.
Adding username
  1. Username registered
Username registered
  1. The username removed from the session
Username removed from the session

How to use Flask-Session

Flask-Session is an extension of Flask that offers extra support for managing sessions in the Flask application. It is designed to enhance the capability of session handling by providing various session storage types and configurations in Flask.


You need to install the package before implementing it in the Flask application. You can install it by running the following command using pip.


The previous code is modified to use the Flask-Session. The following changes have been made to the code:

  • from flask_session import Session: The Session class is imported from the flask_session module.
  • app.config['PERMANENT_SESSION_LIFETIME']: The PERMANENT_SESSION_LIFETIME configuration is used to set the expiration time of the active session.
  • app.config['SESSION_TYPE']: This is used to set the session storage type. In this case, the storage type is set to "filesystem" which means that the session data will be stored in the server’s filesystem.
  • app.config['SESSION_FILE_DIR']: This is used to set the path to the directory where the session data will be stored.
  • Session(app): The Flask-Session is initialized with the Flask application (app). This will connect the Flask-Session with the app and all the configurations will be applied.

Most Commonly Used Configuration Keys

The following are the most commonly used configuration keys provided by Flask-Session.

Configuration KeyDescription
SESSION_TYPESpecifies which type of session interface to use. Built-in session types:
null: NullSessionInterface (default)
redis: RedisSessionInterface
memcached: MemcachedSessionInterface
mongodb: MongoDBSessionInterface
sqlalchemy: SqlAlchemySessionInterface
SESSION_PERMANENTWhether use permanent session or not, default to be True
PERMANENT_SESSION_LIFETIMEThe lifetime of a permanent session in seconds
SESSION_FILE_DIRThe directory where session files are stored. Default to use the flask_session directory under the current working directory.

Flask-Session provides additional configuration keys that eventually enhance the capabilities of the session provided by Flask. You can refer to the official docs for more.


The session is the duration of a user’s interaction with an application, beginning with logging in and ending when the user logs out. During this time, the application is able to store and manage user-specific data across multiple requests.

Flask session can be used to store and manage data on the server, and Flask-Session can be used to extend the flask session‘s capability.

Let’s recall what you’ve learned:

  • What is a session?
  • How to use session in Flask by creating a Flask app and storing user-related data in the session.
  • How to use Flask-Session to add additional application configurations such as session storage type and directory.

🏆Other articles you might be interested in if you liked this one

How to display messages using flash() in Flask app?

How to structure Flask app using Blueprint?

Upload and display images on the frontend using Flask in Python.

How to unit testing of the code in Python using unittest module?

How to connect the SQLite database with the Flask app using Python?

How to implement __getitem__, __setitem__ and __delitem__ in Python?

That’s all for now

Keep Coding✌✌