Flask Sessions


This tutorial tackles everything about Flask sessions. It also shows the Web Application of Flask.

What are Flask Sessions?

The operations of Flask Sessions are similar to those of Flask cookies. The only exception is that they are stacked away on the server.

The period with which a user is logged on to a server is termed a session. The data covered during this session are stored on the server.

Every session has an ID (coded with a confidential key). Sessions make use of special ID to recover values that are stacked away. When sessions are created, the user's computer stacks away the special ID contained in the cookie. Anytime when it is requested from the server it is returned.

When the user on another occasion visits the site, it delivers a cookie with the sessions ID. The server interprets the session ID and gets back the fitting data from that session.

Related course: Create Web Apps with Python Flask

Reasons for using Sessions?

From the perspective of a client, keeping data (in cookies form) not a favorable idea. Few other menace Include: Hackers hacking the site by creating and sending false login details and cookies

Most browsers dont permit cookie data of more than 3-4kb. So the amount of data stored in the cookie is fixed.

The security is poor, so storing important data like passwords are not safe in cookies. To deal with that, we store important info regarding users on the server while we keep the session ID and special key on the user's computer as cookies.

Active participation with arranging Sessions in Flask.

Moving straight to the aspect involving coding. There is a dictionary object in Flask termed session, this object is used to located session data.

The syntax is relatively uncomplicated:

session['<title>'] = value

Setting a session is just that simple. To delete same session or in fact any sessions info, we use session.pop('<title>') function

session.pop('<title>', None)  

Let us look at this example:

@app.route('/setsession')
def setsession():
    session['Username'] = 'Admin'
    return f"The session has been Set"
 
@app.route('/getsession')
def getsession():
    if 'Username' in session:
        Username = session['Username']
        return f"Welcome {Username}"
    else:
        return "Welcome Anonymous"
 
@app.route('/popsession')
def popsession():
    session.pop('Username',None)
    return "Session Deleted"

Note, Set session () view sets the session – username to The get session () view will display Welcome Admin if the username is set or will simply return welcome Anonymous otherwise. Finally, the pop session () view will remove the username session from the server. Hence the final code will be:

from flask import Flask, session
 
app = Flask(__name__)
app.secret_key = "xyz"
 
@app.route('/setsession')
def setsession():
    session['Username'] = 'Admin'
    return f"The session has been Set"
 
@app.route('/getsession')
def getsession():
    if 'Username' in session:
        Username = session['Username']
        return f"Welcome {Username}"
    else:
        return "Welcome Anonymous"
 
@app.route('/popsession')
def popsession():
    session.pop('Username',None)
    return "Session Deleted"
 
app.run(host='localhost', port=5000)

The confidential-key should be referred to considering the fact that sessions make do with the confidential key for encryption.

Implementation of the code

#setsession Here you go. Now launch the server and access "set session"

#getsession Now after accessing the “get session” URL, welcome Admin has to be displayed. So try it out

#popsession Awesome, the next step is to pop/destroy the session and re-visit the get session URL

#getsessionAnonymous Now go to "/get session"

Conclusion

Thats all about the Flask sessions. We hope you’ve learned enough so you can program your Flask session. Enjoy coding! And in case of any question, don’t hold back, reach out to us via the comment section.

Related course: Create Web Apps with Python Flask