Updated April 11, 2023
Definition on Flask Session
Flask session is defined as a technique in flask utility that acts as an extension to provide support for sessions in the server-side in the flask application built. But, do we know what is Flask? In short, Flask is a lightweight framework or in other words microframework that allows building web applications. Session in Flask has a concept very similar to that of a cookie, i.e. data containing identifier to recognize the computer on the network, except the fact that session data is stored in a server. The object that it is instantiated with that contains the data is a dictionary object that includes key-value pair of session variables and corresponding values.
Syntax
Now in this section, we will go through some important syntax that takes into account the basic utilities of the flask session and is equally important to have a glance at first before we know about the working so that understanding the working of flask session is painlessly relatable.
Installing the Flask cache extension through any terminal:
easy_install Flask-Session
OR
pip install Flask-Session
Set a certain value to the session:
Session[<variable name>] = <value>
Remove a session variable:
session.pop(<variable name>, none)
Define the validity of a session for x minutes:
app.permanent_session_lifetime = timedelta(minutes=<numerical minutes>)
Define the validity of a session permanently:
session.permanent = True
How session works in Flask?
In the introduction, we got a brief understanding of session as another way to store data between requests which are user-specific. The time interval of session is from the time the client logs in to a server till it logs out and is coupled with a session id. So, any identification that needs to be made in terms of the user of the session is stored in the data.
The working of a session in flask starts from the point of using it. For using a session, one must set a secret key. This secret key is a value set to a parameter in the application and is used for anything that requires authentication so as to safeguard against any attacks and tampering. Using the session object in one can set or get the session data. Now, when a user uses sessions the data is stored as a cookie and this cookie has a special name to itself named as a session cookie. The reason of it being named as a special cookie and making itself differ from an ordinary cookie is that this cookie is cryptographically signed by Flask. Cryptographically signing it means that anyone has the permission to view the contents in the cookie but can’t modify it. Modification is only possible if one has the secret key that is used to sign the cookie.
Now that the session cookie is set, the authenticity of the cookie is verified for every subsequent request to the server. This verification is done by unsigning with the same secret key with which it is signed. In case of failure of unsigning the content of the cookie is discarded, and a new cookie is sent to the browser and made into a session cookie!
It will be easier to understand if we can learn about the working of a session through a simple example of a user entering into a session where the details will be stored till they log out.
First, we will import the session object in Flask using:
from flask import Flask, redirect, url_for, render_template, request, session
Now, we need to pass the secret key that will be used for signing the cookie when the session object is created. This is done by:
app.secret_key = "27eduCBA09"
Next step is to create the session data. As we know from our earlier paragraphs that sessions are dictionary in python that consists of key and value, hence we assign a new dictionary key as follows:
session["<newKey>"] = '<value01>'
The next thing in line is if we need the information of the session in any step, we can easily grab that information and store it in a variable just as we see it in the below method:
Variable = session["<name of Key>"]
Now assume that if some user logs out from a web page, we will need to remove the session key from the dictionary so that all the information regarding the session is removed from the variable space. We use the method which is mentioned below:
session.pop("<name of Key>", None)
With this, we have a clear understanding of how session works. Just an additional thing, is that we should be able to manage how long a session last which by default is as long as the browser is open. But as a developer, we can make that session as permanent (essentially valid for 30 days) or define the duration of the session as:
For a pre-defined time:
app.permanent_session_lifetime = timedelta(minutes=<numerical minutes>)
For permanent session:
session.permanent = True
Examples
Let us discuss examples of Flask Session.
Example #1
Installing Flask cache extension through any terminal.
Code:
pip install Flask-Session
Output:
Example #2
Set a certain value to the session.
Code:
from flask import Flask, redirect, url_for, render_template, request, session
from datetime import timedelta
appFlask = Flask(__name__)
appFlask.secret_key = "27eduCBA09"
appFlask.permanent_session_lifetime = timedelta(minutes=5)
@appFlask.route("/login")
def login():
session["user"] = "user1"
return '''<h1>The session value is: {}</h1>'''.format(session["user"])
if __name__ == "__main__":
appFlask.run(debug=True)
Output:
Example #3
Remove a session variable.
Code:
from flask import Flask, redirect, url_for, render_template, request, session
from datetime import timedelta
appFlask = Flask(__name__)
appFlask.secret_key = "27eduCBA09"
appFlask.permanent_session_lifetime = timedelta(minutes=5)
@appFlask.route("/login")
def login():
session["user"] = "user1"
return '''<h1>The session value is: {}</h1>'''.format(session["user"])
@appFlask.route("/logout")
def logout():
variable = session["user"]
session.pop("user", None)
return '''<h1>The deleted session is: {}</h1>'''.format(variable)
if __name__ == "__main__":
appFlask.run(debug=True)
Output:
Conclusion
In this article, we have got a hands-on experience of how session works in Flask along with the in-depth working of the session. We need to make sure that the secret code we use must be such that, one can’t guess it easily otherwise the sensitive information in cookies is bound to get compromised. Rest, session is the most secure way to deploy the application prepared and experimentation lies in hands of the reader now!
Recommended Articles
This is a guide to Flask Session. Here we discuss the introduction, syntax and working of session in flask along with examples and code implementation. You may also have a look at the following articles to learn more –