Sessions in Flask

by Alex
Sessions are another way to store data of specific users between requests. They work in a similar way to cookies. To use a session, you must first configure a private key. The session object from the flask package is used to set up and retrieve session data. The session object works like a dictionary, but it can also track changes. When sessions are used, the data is stored in the browser as a cookie. The cookies used to store session data are session cookies. However, unlike regular cookies, Flask cryptographically marks session cookies. This means that anyone can see the contents of the cookie, but cannot change it without having a secret key to sign. Once the session cookie is set, each subsequent request to the server authenticates the cookie with the same secret key.
If Flask fails to do so, then its content is rejected and the browser receives a new session cookie. Those familiar with sessions from the PHP language will notice that sessions in Flask are slightly different. In PHP the session cookie does not store session data, only the session id. This is a unique string that PHP creates to associate the session data with the cookie. The session data is stored on the server as a file. When a user makes a request, PHP uses the session id to find the session data and display it in code. This type of session is known as server-side sessions, and those used in Flask are called client-side sessions. By default, there is not much difference between cookies and client sessions in Flask. As a result, client sessions suffer from the same drawbacks as regular cookies:
  • Cannot store sensitive information such as passwords.
  • Gives unnecessary load at each request.
  • Cannot store more than 4KB.
  • Limited in total number of cookies per site

and so on. The only real difference between cookies and client sessions is that Flask ensures that the contents of the session cookie cannot be changed by users (unless they have a secret key). To use client sessions in Flask, you can either write your own session interface or use extensions such as Flask-Session or Flask-KVSession.

How to read, write and delete session data

The following code demonstrates how you can read, write, and delete session data. Let’s open the file to add the following code after the article() view function:

from flask import flask, render_template, request, redirect, url_for, flash, make_response, session
def visits():
   if 'visits' in session:
	session['visits'] = session.get('visits') + 1 # read and update session data
	session['visits'] = 1 # setting session data
   return "Total visits: {}".format(session.get('visits'))

def delete_visits():
    session.pop('visits', None) # delete visits data
   return 'Visits deleted'

It’s worth noting that the session object is used as a normal dictionary. If the server is not running, you need to start it and go to https://localhost:5000/visits-counter/. The page will have a visit counter:

Sessions in Flask

To increase it, you have to refresh the page several times.Sessions in FlaskFlask sends a session cookie to the client only when a new session is created or an existing one is modified. The first time you visit https://localhost:5000/visits-counter/, the else body in the visits() view will be executed, resulting in a new session. When a new session is created, Flask will send the session cookie to the client. Subsequent requests to https://localhost:5000/visits-counter will execute code in the if block that updates the session’s visits counter value. When the session changes, a new cookie will be created, so Flask will send a new session cookie to the client. To delete the session data you have to go to https://localhost:5000/delete-visits/.

Sessions in Flask

If you open https://localhost:5000/visits-counter now , the visit counter will show 1 again.Sessions in Flask By default, the session cookie exists until the browser closes. To extend the lifetime of a session cookie, you must set the permanent attribute of the session object to True. When permanent is True, the lifetime of the session cookie is equal to permanent_session_lifetime. the permanent_session_lifetime is the datetime.timedelta attribute of the Flask object. Its default value is 31 days. You can change it by selecting a new value for the permanent_session_lifetime attribute using the PERMANENT_SESSION_LIFETIME setting key.

import datetime

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

Like request, the sessions object is available in templates.

Changing session data

Note: you must remove the cookies set by the local host before following the instructions. Most of the time, the session object automatically picks up the changes. But there are cases, such as changing the structure of the data being changed, that are not automatically picked up. For these cases you have to set the modified attribute of the session object to True. If you don’t do this, Flask won’t send the updated cookie to the client. The following code shows how to use the modified attribute of the session object. Let’s open the file to add the following code before the delete_visitis() view.

def updating_session():
    res = str(session.items())

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

   return res

On the first visit to https://localhost:5000/session/, the code in the else block will be executed. It will create a new session with the session data as a dictionary. A subsequent request to https://localhost:5000/session/ updates the session data by setting the number of “pineapples” to the value of 100. In the next line, the attribute modified is set to True, because without it Flask will not send the updated session cookie to the client. If the server is not running, it should be started and go to https://localhost:5000/session/. An empty session dictionary will be displayed, because the browser does not yet have a session cookie to send to the server: Sessions in Flask If the page is reloaded, the session dictionary will already contain “10 pineapples”:Sessions in FlaskReloading the page a third time, you can see that the session dictionary has “pineapples” as 100, not 10: Sessions in Flask The session object picked up the change thanks to the modified attribute. You can verify this by deleting the session cookie and commenting out the line where the modified attribute is set to True. Now after the first request, the value of the session dictionary will be “10 pineapples”. That’s all you need to know about Flask sessions. And it is important not to forget that Flask sessions are client sessions by default.

Related Posts