Session Management in Python, Flask

Introduction

You will see here how to do session management in Python Flask. Session management in Python flask generally involves starting session, removing item from session, clearing item from session, updating item in session.

You will see in subsequent sections later how to put value or an item into session, updating value in session, clearing session completely, removing value from session and removing a dictionary items from session.

Prerequisites

Python 3.8.1 – 3.9.1, Flask 1.1.1 – 1.1.2, Windows 10 64 bit

Configuring Flask

Create below configuration before you use session or flash from Flask framework.

The secret key ideally should be the encrypted one.

from flask import Flask

app = Flask(__name__)
app.secret_key = "secret key"

Session

Flask-Session is an extension for Flask that adds support for Server-side Session to your application.

The session can be defined as the duration for which a user logs into the server and logs out.

The data which is used to track this session is stored into the temporary directory on the server.

The session data is stored on the top of cookies and signed by the server cryptographically.

Store and Retrieving Session Items

Simply you put an item into session as a key/value pair. Use below example to put an item into session and render a template file.

@app.route('/')
def app_session():
	session['msg'] = 'Hello'
	return render_template('template.html')

To retrieve item from session, use below code:

session.get('msg')

To print on console you can use below code:

print(session.get('msg'))

The above will give you output Hello in the console.

To retrieve item from session into template file, use below code:

{% if 'msg' in session %}
	{{ session['msg'] }}
{% endif %}

The above code snippets will give output as:

session management in python flask

To update the item into session use below code snippets. You must use session.modified = True to update value into session variable, otherwise you won’t be able to update the value for an item in session.

session['msg'] = 'Hello'
session.modified = True
session['msg'] = 'Hello, Soumitra'
print(session.get('msg'))

The above code will give you output as Hello, Soumitra.

To remove the item from the session use below code:

session.pop('msg')

If you print after removing item from session using code print(session.get('msg')) then you will get output as None.

To put multiple items into session, you can use below example:

session['hi'] = 'Hi'
session['hello'] = 'Hello'

for key, val in session.items():
	#print(key + ' -> ' + val)
	print(key, ' -> ', val)

From the above code snippets, you will get below output:

hi -> Hi
hello -> Hello

If you want to remove all items at a time from the session then you can use below code:

session.clear()

To put and iterate dictionary item into session, you can use below example:

itemArray = {'name' : 'Soumitra', 'email' : 'soumitra@roytuts.com', 'address' : 'Earth'}
session['item'] = itemArray

for key, val in session['item'].items():
	print(key + ' -> ' + val)

The above will give you below output:

name -> Soumitra
email -> soumitra@roytuts.com
address -> Earth

You can also iterate in different way as shown:

if 'item' in session:
	for item in session['item'].items():
		print(item)

The above code will produce below output:

('name', 'Soumitra')
('email', 'soumitra@roytuts.com')
('address', 'Earth')

To remove a particular key/value from dictionary, for example, to remove a name from the above dictionary, use session['item'].pop('name'). Make sure you use session.modified = True while you remove.

So you will get final output as:

email -> soumitra@roytuts.com
address -> Earth

To remove the whole dictionary you can use session.pop('item'). You can also use second parameter as None, i.e., session.pop('item', None) and it will prevent raising error keyError if the key at the first parameter is not found in the session.

Let’s say you are putting below dictionary item into session variable:

itemNestedArray = { 'key' : {'name' : 'Soumitra', 'email' : 'soumitra@roytuts.com', 'address' : 'Earth'}}
session['item'] = itemNestedArray

Iterating dictionary item using for loop:

if 'item' in session:
	for item in session['item'].items():
		print(item)

The above code will produce below output:

('key', {'name': 'Soumitra', 'email': 'soumitra@roytuts.com', 'address': 'Earth'})

To remove the whole dictionary you can use session['item'].pop('key').

Source Code

Download

Leave a Reply

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