Python Flask-Flask Session

Flask Session

The session is used to store user-specific data between requests. It works similarly to cookies. Set a secret key to use sessions. The session object of the flask package is used to set and get session data. session object works like a dictionary but it can also keep track modifications.

When we use sessions the data is stored in the browser as a cookie. The cookie used to store session data is a known session cookie.  Anyone can view the contents of the cookie, but can’t modify the cookie unless he has the secret key used to sign the cookie.
Once the session cookie is set, every subsequent request to the server verifies the authenticity of the cookie by unsigning it using the same secret key. A new session cookie is sent to the browser when the flask fails to unsign the cookie then its content is discarded.

Sessions in Flask is a little different than PHP. In PHP, session cookie doesn’t store session data instead it only stores a session id. The session id is a unique string PHP creates to associate session data with the cookie. The session data is stored on the server in a file. PHP uses the session id to retrieve session data and makes it available in your code by receiving upon a request from the client. This type of session is known as server-side sessions and the type of sessions Flask provides by default is known as client-side sessions.

By default, there is not much difference between cookies and client-based sessions in Flask. The client-based sessions suffer from the same drawbacks the cookies have like:

  • It Can’t store sensitive data like passwords.
  • An additional payload on every request.
  • It Can’t store data more than 4KB.
  • Limit on the number of cookie per website and so on.
The only difference between cookies and the client-based session is that Flask guarantees that the contents of the session cookie is not tempered by the user (unless he has the secret key).
If you want to use server-side sessions in Flask, you can write your own session interface or use extensions like Flask-Session and Flask KVSession.
How to Read, Write and Delete Session data
The following listing demonstrates how we can read, write, and delete session data. Open main2.py file and add the following code just after the spark() view function:
flask_app/main2.py
from flask import Flask, render_template, request, redirect, url_for, flash, make_response, session
@app.route('/spark-counter/')
def spark():
    if 'spark' in session:
        session['spark'] = session.get('spark') + 1  # reading and updating session data
    else:
        session['spark'] = 1 # setting session data
    return "Total visits: {}".format(session.get('spark'))

@app.route('/delete-spark/')
def delete_spark():
    session.pop('spark', None) # delete spark
    return 'spark deleted'
Start the server if not already running and
visit
http://localhost:5000/spark-counter/.Refresh the page several times more to increase the spark count.
Flask sends the session cookie to the client only when you create a new session or modify an existing session. When you visit http://localhost:5000/spark-counter/ page for the first time, the body of the else block is executed in the spark() view function and creates a new session. As we are creating a new session, Flask sends the session cookie to the client. The subsequent requests to http://localhost:5000/spark-counter/ execute the code in the if block, where are updating the value of visits, counter in the session. Modifying a session means that a new cookie needs to be created that’s why Flask again sends the new session cookie to the client.
To delete the session data spark http://localhost:5000/delete-spark/.
If you now visit http://localhost:5000/spark-counter/the session cookie will last for permanent_session_lifetime. The permanent_session_lifetime is a DateTime. We can change that by specifying a new value to permanent_session_lifetime attribute or by setting a PERMANENT_SESSION_LIFETIME configuration key.

import datetime
app = Flask(__name__)
app.permanent_session_lifetime = datetime.timedelta(days=365)
# app.config['PERMANENT_SESSION_LIFETIME'] = datetime.timedelta(days=365) #

Just like the request object, the session object is also available in the templates.

Modifying Session Data

We should delete all the cookies set by the localhost before modifying all the data. Most of the time session object automatically picks up modifications on it.  In some cases, modifications to mutable data structures are not picked up automatically. For such cases, we should set the modified attribute of the session object to True. If we don’t set a modified attribute to True Flask will not send the updated session cookie to the client. The following listing demonstrates how to use the modified attribute of the session object. Open the main2.py file and add the following code just before the delete_spark() view function.
flask_app/main2.py
@app.route('/session/')
def updating_session():
    res = str(session.items())

    cart_item = {'apples': '10', 'banana': '20', 'pineapples': '30'}
    if 'cart_item' in session:
        session['cart_item']['apples'] = '100'
        session.modified = True
    else:
        session['cart_item'] = cart_item

    return res
#...

The first time you visit http://localhost:5000/session/ the code in the else block is executed and it creates a new session where session data is a dictionary. The subsequent request to http://localhost:5000/session/ updates the session data by setting apples to count to 100. And next, we are setting the modified attribute to True because without it Flask will not send the updated session cookie to the client.

Start the server if not already running and visit http://localhost:5000/session/. The browser had no session cookie to send to the server so you will be displayed an empty session dictionary.

Reload the page again and you will be displayed session dictionary with 10 apples as follows:

Reload the page for the third time and you will see the session dictionary with 100 apples instead of 10 as follows:

The session object has picked up this modification because of the modified attribute. By deleting the session cookie and commenting out the line which sets the modified attribute to True we can verify it. Now after the first request you will always be displayed session dictionary with 10 apples.

It completes all you need to know about sessions in Flask. Don’t forget the default sessions in Flask are client-side sessions.