Communication between web browsers (clients) and servers is completed via HTTP( Hyper Text Transfer Protocol). It is a stateless protocol. This means a HTTP server does not keep track of any state information. The server will not remember whether a client has visited it before. Each time a client visits the server behaves with it as a new client. The sessions make a stateless protocol stateful.
Django has a session framework which handles cookies. In cookies we store session_key. It is a unique 32-character-long random string. A session_key can be considered as a token (a sequence of characters). It identifies a unique session within a particular web application. Sessions are used to abstract the receiving and sending of cookies, data is saved on server-side, and a session_key is stored in the client-side cookie for identification.
Setting Up Sessions
By default, Django saves sessions information in database (django_session table). But we can configure the engine to store information using other ways. Like in file or in cache. There are several ways of storing sessions:
- Database Backed Sessions
To use database backed sessions in django we need to add ‘django.contrib.sessions’ in ‘INSTALLED_APPS’. So, it is mandatory to run ‘makemigrations’ & ‘migrate’ command to use session. It will require tables.
- File Based Sessions
Set the ‘SESSION_ENGINE setting to ‘django.contrib.sessions.backends.file’. We can also use SESSION_FILE_PATH setting to control where django stores session files. But we will have to make sure that our web browser has the permissions to read & write to this location.
- Cookie-Based Sessions
The Django session framework is entirely cookie based. Set the ‘SESSION_ENGINE” setting to ‘django.contrib.sessions.backends.signed_cookies’. The session is stored using Django’s tools for cryptographic signing and the SECRET_KEY setting.
- Cached Sessions
You may need to use a cache-based session backend for better performance. You’ll have to configureyour cache to store session data using Django’s cache system.
Database – Backed Session
To use database-backed sessions in django we will have to enable sessions in project settings.py, by adding some lines to the MIDDLEWARE_CLASSES and the INSTALLED_APPS options. This should be done while creating the project, but it’s always good to know,
so MIDDLEWARE_CLASSES should have −
MIDDLEWARE_CLASSES = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', ... ]
And INSTALLED_APPS should have −
INSTALLED_APPS = [ ... 'django.contrib.sessions', ... ]
When we create a new project with the startproject command these are automatically added by Django. When SessionMiddleware is activated, each HttpRequest object(the first argument to any Django view function) will have a session attribute. It is a dictionary-like object. And it has following standard dictionary methods:
setitem(key, value) -sets the value a key in the session
request.session[‘key’] = ‘value’
returned_value = request.session[‘key’]
get(key, default=None) – brings the value of the key returns None if doesn’t exists.
value = request.session.get(‘key’, default = None)
delitem(key) – deletes item from the session.
This will raise KeyError if the given key isn’t already in the session.
pop(key, default=__not_given) – returns & deletes the item.
keys()-returns all the keys stored in the session.
all_keys = request.session.keys()
items()-returns all the items stored in the session.
all_items = request.session.items()
clear() – clears the session
Using Sessions In Views
We can use request.session to read & write in our view.
def sessions_demo(request): # Number of visits to this view # As counted in the session variable. num_visits = request.session.get('num_visits', 1) request.session['num_visits'] = num_visits + 1 return HttpResponse(num_visits)
Here we have accessed the value ‘num_visits’. It was in ‘sessions’ before. Then we have incremented the value each time we visit (refresh) the url. Let’s see in our browser.
Each time we refresh the page the value increments. Now we will add our own key & value in the session.
we can check our sessionid in our browser.
Besides, we can check our ‘session_key’ using ‘session_key’ attribute.
session_key = request.session.session_key #output g4mb4ye2ygzrd1miczzjshterrnrwevz
def set_session (request): request.session['username'] = 'ratul' request.session['email'] = 'firstname.lastname@example.org' persons = Person.objects.all() for person in persons: request.session[str(person.id)] = person.full_name return HttpResponse("Session Set")
Let’s check items that we have stored in our session.
def get_session(request): name = request.session.get('username',default='None') email = request.session['email'] # get all the items of session all_persons = request.session.items() return HttpResponse(name + '-' + email)
def delete_session_item(request): del request.session['username'] #try to get the name after deleting if not avaiable #get() will show none name = request.session.get('username') return HttpResponse(name)
Want to know more about sessions? Read the codes of Django sessions in django.contrib.sessions.backends.base.SessionBase. It is the base class of all session objects.