How to Use Session in Flask?

Interactive Online Courses: Elevate Skills & Succeed Enroll Now!

In this tutorial, we will learn about session in flask with example, its working, uses and much more. Let’s start!!!

Session in Flask

Session data in flask is saved on the client, just as cookies. A client’s time spent logging in and out of a server is known as a session. The client browser stores the data that must be kept around for this session. Each client’s session is given a unique Session ID. The persistent data is kept on account of cookies and is cryptographically signed by the server. A defined SECRET KEY is required by a Flask application for this encryption.

A dictionary object called a session object also contains key-value pairs for session variables and their corresponding values. Your application will now support Server-side Session thanks to the Flask-Session extension. If you’re using an earlier version of Flask, see Compatibility for Old and New Sessions. Flask 0.8 or later is required.

A Flask addon called Flask-Session allows your application to handle server-side sessions. The period of time between a client’s initial login and their final logout is known as a session. The information that must be stored in the session is kept on the server in a temporary directory.

The server cryptographically signs the data in the Session and stores it on top of cookies. Each customer will have a separate session where their unique data will be saved.

A cookie and a session both have very similar concepts. The session data, however, is kept on the server. The period of time between a user’s login and logout on the server is known as a session. The transient subdirectory on the server is where the information needed to monitor this session is kept. The session data is kept on top of cookies and cryptographically signed by the server.

In Flask, a session object is used to track session data. The session object is essentially a dictionary entity that contains key-value pairs of session parameters and their associated values. This allows the Flask application to maintain state across multiple requests from the same client. The session object can be used to store data that needs to be persisted across requests, such as user authentication status or shopping cart contents. It is a powerful feature of Flask that enables developers to build more sophisticated web applications with a greater degree of interactivity and personalization.

Use the statement, for instance, to set the session variable “username.”

Session[‘username’] = ‘applicant’

The pop() method is useful to remove a session variable.

session.pop('username', None)

Use the command below to install the extension.

$ pip install Flask-Session

Setting up a Session in Flask

Direct access is not made use of with the Session instance. Always make use of flask session. Each of us as users get our own copy of the session thanks to the initial line from the flask’s design.

from flask import Flask, render_template, redirect, request, session
from flask_session import Session

You should never use the Session object directly; instead, use flask.session:

from flask import Flask, session
from flask.ext.session import Session
data = Flask(__name__)
# Check Configuration section for more details
SESSION_TYPE = 'redis'
app.config.from_object(__name__)
Session(data)
@app.route('/set/')
def setting():
    session['key'] = 'value'
    return 'okay'
@app.route('/get/')
def getting():
    return session.get('key', 'not fixed')

IIlustration

from flask import *  
application = Flask(__name__)  
application.secret_key = "abc"  
@application .route('/')  
def demo():  
    result = make_response("<h4>session variable is set, <a href='/get'>Variable</a></h4>")  
    session['response']='session#1'  
    return result ;  
@application route('/get')  
def get():  
    if 'response' in session:  
        s = session['response'];  
        return render_template('first.html',name = s)  
if __name__ == '__main__':  
    application .run(debug = True) 

first.html

<html>  
<head>  
<title>getting the session</title>  
</head>  
<body>  
<p>The session's value is set to: <strong>{{title}}</strong></p>  
</body>  
</html>

Using Sessions, log into the flask’s application.

Here, we’ll build a login app in a flask that displays the user the following home page. We cannot browse the account directly without logging in, thus if we click view profile without first logging in, a warning will appear.

When a user visits the login page, the application displays the screen where the user must input their email address and password. Now, our application sends the user to the success page after receiving any random, legitimate email address and password.

The session is implemented via this straightforward login application, which was created with Python Flask. The main controller in this case is the Flask script login.py, which has the view methods home(), login(), success(), logout(), and profile() that are connected to the corresponding URL mappings (/, /sign_in, /successful, /sign_out, and /account).

login.py

from flask import *  
application = Flask(__name__)  
application.secret_key = "ayush"  
@application.route('/')  
def demo():  
    return render_template("demo.html")  
@application.route('/sign_in')  
def sign_in():  
    return render_template("sign_in.html")  
@app.route('/success',methods = ["POST"])  
def successful():  
    if request.method == "POST":  
        session['email']=request.form['email']  
    return render_template('successful.html')  
@app.route('/sign_out')  
def sign_out():  
    if 'email' in session:  
        session.pop('email',None)  
        return render_template('sign_out.html');  
    else:  
        return '<p>Signed out successfully</p>'  
@application.route('/profile')  
def account():  
    if 'email' in session:  
        email = session['email']  
        return render_template('account.html',name=email)  
    else:  
        return '<p>Log in</p>'  
if __name__ == '__main__':  
    application.run(debug = True)

demo.html

<html>  
<head>  
<title>demo</title>  
</head>  
<body>  
<h3>Hello World</h3>  
<a href = "/sign_in">sign_in</a><br>  
<a href = "/account">Access Account</a><br>  
<a href = "/logout">Log out</a><br>  
</body>  
</html>  

login.html

<html>  
<head>  
    <title>Sign_in</title>  
</head>  
<body>  
    <form method = "post" action = "http://localhost:5000/success">  
        <table>  
            <tr><td>Email Id</td><td><input type = 'email' name = 'email'></td></tr>  
            <tr><td>Passcode</td><td><input type = 'password' name = 'Passcode'></td></tr>  
            <tr><td><input type = "submit" value = "Accept"></td></tr>  
        </table>  
    </form>  
</body>  
</html> 

successful.html

<html>  
<head>  
<title>Successful</title>  
</head>  
<body>  
    <h2>Sign in successful</h2>  
    <a href="/profile">View Account</a>  
</body>  
</html>  
sign_out.html
<html>  
<head>  
    <title>Sign out</title>  
</head>  
<body>  
<p>Signed Out Successfully Click <a href="/login">here</a> to Sign in again</p>  
</body>  
</html>

sign_out.html

<html>  
<head>  
    <title>Sign out</title>  
</head>  
<body>  
<p>Signed Out Successfully Click <a href="/login">here</a> to Sign in again</p>  
</body>  
</html>

Uses of sessions in Flask

Sessions are an important feature of Flask that allow developers to store data across multiple requests from the same client. Here are some common use cases for sessions in Flask:

1. User authentication: Sessions can be used to keep track of whether a user is logged in or not, and to store information about the user such as their username or role.

2. Shopping carts: Sessions can be used to store items that a user has added to their shopping cart, so that the items are preserved across different pages of the site.

3. Form data: Sessions can be used to store data that a user has entered into a form, so that it is not lost when the user navigates away from the page.

4. Customization: Sessions can be used to store user preferences or settings, such as the user’s preferred language or display options.

5. Analytics: Sessions can be used to track user behavior and activity across multiple requests, which can be useful for generating analytics and insights.

How does the session work in Flask?

In Flask, sessions work by using a client-side cookie to store a unique session ID for each user. When a user makes a request to the Flask application, the server checks if a session cookie exists. If it doesn’t, a new session ID is generated and stored in a cookie on the user’s browser.

The session ID is used to associate subsequent requests from the same user with their session data, which is stored on the server-side. This allows the Flask application to keep track of user state across multiple requests.

To store data in a session, developers can use the session object provided by Flask. This object behaves like a dictionary, allowing developers to store and retrieve data using keys and values.

For example, to store a user’s name in a session, you could use the following code:

from flask import session

session['username'] = 'Alice'

To retrieve the user’s name from the session in a subsequent request, you could use the following code:

from flask import session

username = session.get('username')

It’s important to note that the data stored in a session is stored on the server-side, and is not accessible to the client. Only the session ID is stored in the client-side cookie. This helps to prevent security issues such as session hijacking and data tampering.

Overall, sessions are a powerful tool for building dynamic, personalized web applications in Flask. They allow developers to create applications that remember and respond to user behavior, preferences, and actions, leading to a more engaging and interactive user experience.

Conclusion

A flask session is a method used in the flask utility that serves as an addition to support identities in the server-side of the flask application created. In a nutshell, Flask is a minimal framework, or microframework, that enables the development of online applications. With the exception of the reality the session data is kept on a server, the notion of a session in Flask is quite comparable to the concept of a cookie.

Session data contains an identifier to identify the networked machine.A dictionary object is used to store key-value pairs of session variables and their corresponding values. This dictionary is used to instantiate an object which contains the session data. The dictionary allows easy access to the session variables and their values. It is a convenient way to store and manage session data in a web application. The session object can be used to persist data across multiple requests, and can be accessed by the server-side code to perform various tasks based on the session data.

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

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