Flask Sessions

Flask sessions are an important feature of the Flask framework that allow you to store and manage user-specific data across multiple requests.

In this article, You will learn the concept of Flask sessions in detail, and discuss their importance in Flask web development.



What are Flask Sessions?

Flask sessions are a way to store user-specific data across multiple requests. They provide a mechanism for a Flask application to keep track of user information, such as login credentials, shopping cart contents, and user preferences.

Flask sessions are stored on the server-side, and a session ID is used to associate the user’s data with their session.

When you utilize session data, it is stored on the client-side similar to cookies. Your session starts when you log into a server and ends when you log out. During this period, the data needed to persist is saved in your browser. A unique Session ID is assigned to your session, and the session data is encrypted using cookies that are cryptographically signed by the server.

To encrypt the session data, you will need a pre-defined SECRET_KEY for your Flask application. Additionally, the session object is a dictionary-like object that contains key-value pairs of session variables and their corresponding values.


Why Flask Sessions Are Important?

There are various reasons why Flask sessions are significant.

  • Firstly, they permit web applications to retain user-specific data across multiple requests. This feature is particularly vital for applications that necessitate user authentication or maintain a shopping cart.
  • Secondly, Flask sessions offer a secure way to store information. As session data is kept on the server, it remains inaccessible and unalterable by the user.

To define a session variable called ‘client_name‘, you can refer to the following statement as an example:

Session[client_name’] = ’mrx’

If you want to delete a session variable, you can invoke the pop() method:

session.pop(client_name', None)

The below code shows how sessions work in Flask in a simple way. When you go to the URL ‘/’, you will be asked to log in because the ‘client_name’ session variable has not been set.

from flask import Flask, session, redirect, render_template, request, make_response, url_for

app = Flask(__name__)

app.secret_key = 'mrexamples'

@app.route('/')

def index():

   if 'client_name' in session:

      client_name = session['client_name']

      password = session['pwd']

      if client_name and password:

         return f'{client_name} Your account is logged in.<br>' \

            "<b><a href = '/logout'>Log out your account here</a></b>"

      else:

         return redirect('/login')

   return "You are not logged in <br><a href = '/login'></b>" + \

      "Log in your account here</b></a>"

@app.route('/login', methods = ['GET', 'POST'])

def login():

   if request.method == 'POST':

      session['client_name'] = request.form['client_name']

      session['pwd'] = request.form['pwd']

      return redirect(url_for('index'))

   return '''

   <form action = "" method = "post">

      <p>Username*: <input type = text name = client_name /></p>

      <p>Password*: <input type = password name = pwd /></p>

      <p><input type = submit value = Login /></p>

   </form>

   '''

@app.route('/logout')

def logout():

   session.pop('client_name', None)

   session.pop('pwd', None)

   return redirect(url_for('index'))



if __name__ == '__main__':

   app.run(debug = True)

Output

This is what you will see on the screen: there will be a link that says “Log in your account here”.

On the next screen, there will be a link that you can click on. Once you click it, you will be taken to another page where you need to enter the name ‘Harry’ and password ‘12345678’.

The screen will appear with a message saying, “Your account is logged in as Harry.”

Example Explanation

We have created a simple Flask application that allows us to log in and log out of our accounts. We used the Flask framework to create routes for handling different HTTP requests.

We started by importing the necessary modules and creating a Flask application instance. We set the secret_key for the application, which is used for session management.

The ‘/’ route is defined for the index page. The index() function checks if the client_name session variable is set. If it is, the user is considered logged in, and a welcome message is displayed along with a link to the logout page. If the client_name variable is not set, the user is considered not logged in, and a message is displayed along with a link to the login page.

The ‘/login’ route is defined for the login page. The login() function handles user login. It checks if the HTTP method used is POST, meaning the user has submitted the login form. If the form has been submitted, the client_name and pwd session variables are set to the values entered in the form, and the user is redirected to the index page. If the HTTP method is not POST, the login form is displayed.

The ‘/logout’ route is defined for the logout page. The logout() function removes the client_name and pwd session variables, effectively logging the user out.

Finally, the if name == ‘main’ block checks if the script is being run directly, and if it is, starts the Flask application with debugging enabled.


Benefits

  • Flask sessions can authenticate users and maintain their login state across different requests.
  • User data can be stored across requests without relying on cookies or other storage mechanisms using Flask sessions.
  • Session-based applications can be more efficient since session data is stored on the server and not sent back and forth between the client and server on each request.
  • Flask sessions can be customized to meet specific application requirements, such as changing the default session timeout or using a different session storage mechanism.
  • Flask sessions use a secure secret key to prevent tampering with session data and protect user privacy.

Conclusion

Flask session is a handy feature of Flask that enables storing and retaining user data across several requests. It offers advantages like verifying user identity, data retention, better performance, flexibility, and security. Implementing Flask session in Flask applications is effortless and can significantly improve their usability and performance.

We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *