Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages
wb_sunny

Flask Sessions – Setting User Sessions in Flask

Flask Sessions

In this tutorial, we will deal with Flask sessions and use them in the Flask Web Application. So let’s get started.

What are Sessions in Flask?

Sessions function similar to Flask cookies except that these are stored on the server.

A Session is basically the time duration for which the user was logged in the server. The data that’s tracked during the entire session is what is stored in the server.

Each session has a Session ID (encrypted with a secret key). Sessions use a unique id to retrieve the stored values. Whenever a session is created, a cookie containing the unique session id is stored on the user’s computer. and is returned with every request to the server. 

When the user revisits the site, he returns the Cookie containing the session ID. The server then reads the session ID and retrieves the corresponding session data.

Why are sessions used? 

Saving data (in the form of a cookie) on the Client-Side is, in general, not a good idea. Some of the other threats are:

  1. Hackers can send a fake cookie and login as another user to hack the site.
  2. Storing sensitive data like user passwords etc. in cookies is not secure.
  3. We can store only a limited amount of data in cookies since most browsers don’t allow more than 4kb of data.

Hence to Tackle that, We keep all the critical user info on the Server itself and store the session ID/key  instead (as a Cookie) on the Client’s Computer

Hands-On with Setting Flask Sessions

Okay, let us now dive into the coding part. In Flask, a dictionary object called session object is used to track the session data.

The syntax is very simple:

session['<title>] = value

This how you set a session. Now to delete the session information, we use the session.pop(‘<title>’) function

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

Let us consider an 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"

Here,

  • setsession() View sets the session – Username to
  • The getsession() view will display Welcome Admin if the Username session is set or will simply return Welcome Anonymous otherwise
  • Finally, the popsession() view will remove the username session from the server.

Therefore the final code will be:

fom 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 secret_key has to be mentioned since sessions use the secret key for encryption.

Implementation of the code

That’s it! Let us now run the server and go to “/setsession

Set Session
Set Session

Now when we go to the “/get session” URL, we must see Welcome Admin. So let’s try that

Get Session
Get Session

Great, now we will pop/destroy the session and then re-visit the getsession URL

Pop Session
Pop Session

Now go to “/getsession

Get Session Anonymous
Get Session Anonymous

Perfect!

And that’s it!

This was all about Flask Sessions. We hope you’ve learned all you needed to know to set your first Flask session. If you have any questions, don’t hesitate to let us know in the comments. Happy Coding!