Table of contents
1.
Introduction
2.
Flask Session
3.
Why Sessions Are Necessary
4.
Installation
5.
How To Configure Sessions In Flask
6.
Remembering User After Login
7.
Flask-Login
8.
FAQs
9.
Key Takeaways
Last Updated: Mar 27, 2024

Session Management In Flask

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

A session is nearly identical to a cookie in terms of the idea. Cookies are files that websites save on your computer or mobile device when visiting a website, on the other hand, the session data is saved on the server. It may be defined as the time taken by the user to log in and out of a server. The information used to trace this session is saved in the server's temporary directory.

The session data is saved on top of cookies and signed cryptographically by the server.

This article will illustrate with an example to help you understand how session management in flask is handled.

Flask Session

Flask-Session is an extension that supports the Server-side Session management in flask for our application. Now, what exactly is a session? 

A session is the amount of time spent on a particular activity. A user session begins when a user signs in to or uses a specific computer, network, or software service in a computer system. The data to be saved in the session is stored in the temporary directory and the server. Each client will have their session, and their data will be held in their respective session.

Why Sessions Are Necessary

Session management in flask plays a vital role in letting the server know when the user logs in. The choices that the user makes get stored, and therefore, it helps further render the thinking of the options that the user makes, and on top of it, the theme receives verification like specific website settings, etc. It plays a significant role in understanding E-commerce websites and managing the cookies well.

Installation

We can install the session with the following command

$ easy_install flask-session

How To Configure Sessions In Flask

We should always use a flask session rather than a session instance because it can't be used for direct access.

from flask import Flask, render_templates, request, session
from flask_session import Session
You can also try this code with Online Python Compiler
Run Code

 

This is specific to the flask_session library. 

  • SESSION_PERMANENT = False –  Here, the session has a default time limit, after which it will expire.
  • SESSION_TYPE = "file" –   It will get stored in the hard drive or any online ide account. It also acts as an alternative to the database.

 

app = Flask(__name__)
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "file"
Session(app)
You can also try this code with Online Python Compiler
Run Code

Remembering User After Login

We will make two basic pages and their route named welcome.html and login.html.

  • login.html has a form where users can fill in their names and submit.
  • welcome.html is the first main page that will be displayed.

 

@app.route("/")
def welcome():
    return render_template('welcome.html')

@app.route("/login", methods=["POST", "GET"])
def login():
    return render_template("login.html")
You can also try this code with Online Python Compiler
Run Code

 

  • We can capture the username in the session when the user submits the form.
  • Here we are using a dictionary in python where “default” is the key = request.form.get(“default”) is a value.

 

@app.route("/login", methods=["POST", "GET"])
def login():
 # If form is submitted
    if request.method == "POST":
        # Record the user name from the login.html
        session["user_name"] = request.form.get("name")
        # Redirect to the main page
        return redirect("/")
    return render_template("login.html")
You can also try this code with Online Python Compiler
Run Code

 

  • After fetching the user name, we need to verify whether or not the user lands on the welcome page by that session or with that user name exists or not.
  • If the username isn't found, the page will be redirected to the login page.

 

@app.route("/")
def index():
  # Check if the users exist or not
    if not session.get("user_name"):
        # If the username isn't found, the page will be redirected to the login page.
        return redirect("/login")
    return render_template('welcome.html')
You can also try this code with Online Python Compiler
Run Code

 

  • After the information gets successfully remembered, we also need to log out the users.
  • When the user clicks logout, change the user value to none and redirect them to the welcome page.

 

@app.route("/logout")
def logout():
    session["user_name"] = None
    return redirect("/")
You can also try this code with Online Python Compiler
Run Code

 

Let’s see the complete code now:

from flask import Flask, render_template, redirect, request, session
# We should always use Flask.session instead of the Session object for direct access.
from flask_session import Session
app = Flask(__name__)
app.config["SESSION_P"] = False
app.config["SESSION_T"] = "file"
Session(app)

@app.route("/")
def index():
    if not session.get("user_name"):
        return redirect("/login")
    return render_template('welcome.html')

@app.route("/login", methods=["POST", "GET"])
def login():
    if request.method == "POST":
        session["user_name"] = request.form.get("name")
        return redirect("/")
    return render_template("login.html")

@app.route("/logout")
def logout():
    session["user_name"] = None
    return redirect("/")

if __name__ == "__main__":
    app.run(debug=True)
You can also try this code with Online Python Compiler
Run Code

 

Login.html

<!DOCTYPE html>
<html lang="en">
<body>
   <h1> Login </h1>

   <form action="/login" method="POST">
      <input placeholder="Name" autocomplete="off" type="text" name="name">
      <input type="submit" name="Register">
   </form>
</body>
</html>

 

Output

 

Welcome.html

<!DOCTYPE html>

<html lang="en">
<body>
   {% if session.name %}
   You are Registered, {{ session.name }} <a href="/logout">logout</a>.<br>
   {% else %}
   You are not Registered. <a href="/login">login</a>.
   {% endif %}
</body>
</html>

 

Output

 

And here the logout link is used to log out of the page.

Flask-Login

It provides user session management in Flask. It controls the everyday tasks of logging in, logging out, and remembering your users' sessions for a long time.

 

Flask-Login is not restricted to any particular database system or permissions model. The only requirements are that your user objects implement a few methods and that you supply a callback to the extension that can load information from our database object (here it is dictionary object, students).

 

INSTALLATION

Installation can be done through the following extension.

$ pip install flask-login

 

Flask login is effortless to use. Now, let's set up the flask app first.

import flask
app = flask.Flask(__name__)
app.secret_key = 'CODINGNINJAS'
You can also try this code with Online Python Compiler
Run Code

 

We can initiate the work by flask login by establishing a login manager.

 

We'll get a login manager by instantiating it

import flask_login
login_manager = flask_login.LoginManager()
login_manager.init_app(app)
You can also try this code with Online Python Compiler
Run Code

 

Now, we're going to use a dictionary to represent the database of users.

students = {‘ninja@codingninjas.com': {'password': 'ninja123'}}

We must also instruct Flask-Login on loading a student from a Flask request and the session. To do this, we must first define our student object, a

student_loader callback and a request_loader callback.

class Student(flask_login.studentMixin):
    pass
 
@login_manager.student_loader
def student_loader(email):
    if email not in students:
        return
 
    student = Student()
    student.id = email
    return student
 
 
@login_manager.request_loader
def request_loader(request):
    email = request.form.get('email')
    if email is not in students:
        return
 
    student = Student()
    student.id = email
    student.is_authenticated = request.form['password'] == students[email]['password']
 
    return student
You can also try this code with Online Python Compiler
Run Code

 

Now we will define our views, like the student view and will move to the authentication aspect.

@app.route('/login', methods=['GET', 'POST'])
    def login():
        if flask.request.method == 'GET':
            return '''
                   <form action='login' method='POST'>
                    <input type='text' name='email' id='email' placeholder='email'/>
                    <input type='password' name='password' id='password' placeholder='password'/>
                    <input type='submit' name='submit'/>
                   </form>
                   '''
   
        email = flask.request.form['email']
        if flask.request.form['password'] == students[email]['password']:
        student = Student()
        student.id = email
            flask_login.login_student(student)
            return flask.redirect(flask.url_for('protected'))
    return 'Login failed'
@app.route('/protected')
@flask_login.login_required
def protected():
    return 'Logged in as: ' + flask_login.current_student.id
You can also try this code with Online Python Compiler
Run Code

 

We can define the view to logging out the student as well.

@app.route('/logout')
    def logout():
        flask_login.logout_student()
        return 'Logged out'
You can also try this code with Online Python Compiler
Run Code

 

We must define a callback to return failures, and that can be coded as

@login_manager.unauthorized_handler
def unauthorized_handler():
    return 'Unauthorized'
You can also try this code with Online Python Compiler
Run Code

 

Generated  session

FAQs

  1. What is the difference between sessions and cookies?
    Cookies are client-side files that save user information on a local computer. User data is stored in sessions, which are server-side files.  The user determines the lifespan of cookies. The session is over when the user quits the browser or logs out of the application.
     
  2. How to clear a flask session?
    Nothing can be done to clear the session. The contents of the session dictionary will be wiped when the app.config["SECRET KEY"] is changed.
     
  3. What is the use of a session object in a flask application?
    A session object, a dictionary object that comprises a key-value pair of the session variables and their associated values, is used to track the data related to session management in flask.
     
  4. How long does a flask session last?
    The default session duration is 31 days; however, the user must specify the login refresh view in the event of a timeout.
     
  5. Is there any way to quickly clear a session key of a user?
    Use the pop() function to release a session variable. This will remove a session key from the session dictionary object, and the application will not be able to authenticate a value of a missing key.

Key Takeaways

In this article, we have extensively discussed session management in flask and how the whole process works. Session management in flask is one of the most crucial aspects of the application and is very necessary to understand how information is saved and used in a session.

We hope that this blog has helped you enhance your knowledge regarding flask and if you would like to learn more, check out our articles on Code Studio. Do upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass