Performing CRUD Operations with Sessions in Python – Django

Setting Up Sessions


In Django, you can enable sessions from the settings.py by adding some lines to the MIDDLEWARE and the INSTALLED_APPS options.

MIDDLEWARE should have −

‘django.contrib.sessions.middleware.SessionMiddleware’

And INSTALLED_APPS should have −

‘django.contrib.sessions’

By default, Django saves session information in database (django_session table or collection), but you can configure the engine to store information using other ways like: in file or in cache.

CRUD Operations


Read

item_id = str(1)
cart_items = request.session

# Create an empty cart object if it does not exist yet 
if not cart_items.has_key("cart"):
	cart_items["cart"] = {}

# Retrieve single item by key 
cart_items.get(item_id)

# Retrieve all 
cart_items.items()

Add

item_id = str(1)
cart_items = request.session

# Create an empty cart object if it does not exist yet 
if not cart_items.has_key("cart"):
	cart_items["cart"] = {}

product_data = {
	'quantity': 2,
	'date_added': strftime("%Y-%m-%d %H:%M:%S", gmtime())
}

cart_items["cart"][item_id] = product_data
cart_items.modified = True

Edit

item_id = str(1)
cart_items = request.session

# Create an empty cart object if it does not exist yet 
if not cart_items.has_key("cart"):
	cart_items["cart"] = {}

# Edit quantity of item ID: 1 
cart_items["cart"][item_id]["quantity"]  = 3
cart_items.modified = True

Delete

item_id = str(1)
cart_items = request.session

# Create an empty cart object if it does not exist yet 
if not cart_items.has_key("cart"):
	cart_items["cart"] = {}

# Delete an item
try:
	del cart_items["cart"][item_id]
except KeyError:
	pass
cart_items.modified = True


Do you need help with a project? or have a new project in mind that you need help with?

Contact Me