Django Session- Learn the Steps to Manage Sessions in Django

In our previous article, we covered Django Cookies. Let’s take it a step further and look at Session in Django.

Let’s take a quick look at the concept of cookies and look at some of its disadvantages. And how the concept of Sessions helped web developers in making their jobs easier.

What are cookies?

Cookies are text files created and organised by your browser in response to a specific Web-Server request, as we mentioned previously in the article about cookie handling.

The HTTP protocol is stateless. In other words, when you send a request to the server, it has no notion if you are requesting the page for the first time or if you are the same user who has visited the website thousands of times previously.

Because persistence among requests may be used to promote products or display products in a shopping cart, the absence of statelessness was a major issue for e-commerce website developers. Cookies were created to alleviate this difficulty.

Cookie was initially used in the Netscape Browser in 1994 by a programmer named Louis Montulli.

Limitations of Cookies

  • It is possible to trace users.
  • The cookies can be deleted by the client.
  • A cookie can store up to 4096 bytes of information.
  • Cookies can be stored by both the browser and the server.
  • Cookies are plain text files, and attackers can easily intercept cookies that are not delivered via HTTPS.

What exactly are Sessions in Django?

Following these issues with cookies, web developers introduced Sessions, a new and more secure approach.

Let’s take a closer look at its technical term.

Stateless HTTP is used for all communication between web browsers and servers. As the protocol is stateless, messages between the client and server are completely independent of one another; there is no “sequence” or behaviour concept based on prior messages. As a result, if you want a website that keeps track of ongoing client interactions, you’ll have to build it yourself.

Django (and most of the web framework) uses sessions to maintain track of the “state” of a site and a particular browser. Sessions allow you to save any amount of data per browser and make it available to the site anytime the browser connects. Individual session data items are then referred to by a “key,” which both saves and retrieves data.

To identify each browser and its associated session with the site, Django employs a cookie with a unique session id. The real session data is stored by default in the site database (This is preferable to keeping the information in a cookie, which is more vulnerable to unwanted/malicious users.). Django allows you to store session data in a variety of places (cache, files, “safe” cookies), but the default location is a smart and secure choice.

Prerequisites:

Complete all previous tutorial topics, including Django Views and Cookie Handling.

Django Session

Django recognises the importance of sessions on a website and hence it provides middleware and an inbuilt app that enables you to generate these session IDs quickly and easily.

Django Session

“django.contrib.sessions” under Settings.py file, is an application that works on “middleware.SessionMiddleware” and is quite suitable to work with.

The “middleware.SessionMiddleware” is held responsible for generating unique Session IDs. While “django.contrib” is also a helping hand when we are talking about storing our Sessions on the database.

We can see the Django session table in the database when we migrate the application.

Django Session

The django.contrib.sessions application is listed in the settings.py files under the INSTALLED APPS list.

If you want to work on sessions, you’ll need to see if your browser supports cookies.

Of course, you can check that in the settings, but let’s create some view functions and URLs to help you grasp the concepts better.

The class backends.base.SessionBase acts as a base class for all session objects. It includes the following methods listed below.

Method Description
__getitem__(key) It’s used to get the value of a session.
__setitem__(key, value) Its purpose is to set the session value.
__delitem__(key) It’s used to delete session objects.
__contains__(key) It determines whether the container contains the particular session object.
get(key, default=None) It’s used to retrieve the provided key’s session value.

Testing the Cookie-Saving Capability of the Browser

Paste the following code in the views.py file.

Code for cookie_session and cookie_delete:

def cookie_session(request):
    request.session.set_test_cookie()
    return HttpResponse("<h1>TechVidvan</h1>")


def cookie_delete(request):
    if request.session.test_cookie_worked():
        request.session.delete_test_cookie()
        response = HttpResponse("TechVidvan<br> This is your newly created cookie")
    else:
        response = HttpResponse("TechVidvan <br> Sorry!! your browser does not accept cookies")
    return response

set_test_cookie()

When your browser asks or sends a request for this webpage, we use this method to create a test cookie.

test_cookie_worked()

After the browser accepts the cookie, this method returns “True” as a boolean value. Otherwise, the statement is false.

delete_test_cookie()

The test cookie is deleted using this approach.

Now, go to the urls.py file under the root project directory and add the following urls there.

path('Testcookie',views.cookie_session),
path('Deletecookie', views.cookie_delete),

Output 1: Run the browser with /Testcookie

Django Cookie-saving

Output 2: Now run the browser with /Deletecookie

Django Cookie-saving

If you see this message, your browser accepts cookies; otherwise, the browser will give you an unexpected response.

If your results don’t look like the one above, make some changes that create your browser accepts cookies; otherwise, you won’t be able to use this tutorial.

Django Sessions: Creating and Using

Django makes it simple to create session variables and manipulate them.

Django’s request object includes a session attribute that creates, accesses and modifies session variables. This attribute operates as a dictionary, allowing you to declare session names as keys and values.

1: First, we’ll change the views.py file.

def create_session(request):
    request.session['Emp_name'] = 'Raghav'
    request.session['Emp_Email'] = '[email protected]'
    return HttpResponse("<h1>welcome to TechVidvan Employee Portal<br> The Session is Set</h1>")



def access_session(request):
    response = "<h1>Welcome to Sessions of TechVidvan Employee Portal</h1><br>"
    if request.session.get('Emp_name'):
        response += "Emp_Name : {0} <br>".format(request.session.get('Emp_name'))
    if request.session.get('Emp_Email'):
        response += "Emp_Email : {0} <br>".format(request.session.get('Emp_Email'))
        return HttpResponse(response)
    else:
        return redirect('create/')

2: In the urls.py file, add the following urls.

path('Create',views.create_session),
path('Access',views.access_session),

3: Execute the following code:

Search for /Create

Django Cookie Saving

Now search for /Access

Django Cookies and Sessions

The session_key and session_data with high encryption are visible in the database.

Django Creating and using sessions

Understanding the Code:

The code is simple python, but the variables we use have some complicated python coding.

If you request the Access/ URL without first making the Create/ request, you will be immediately redirected to the Create/.

When the Create/ URL is delivered, the SessionsMiddleware executes and generates a unique SessionID, which is saved as a cookie for the user locally on the browser.

This cookie, together with the request and sessions, is now delivered to the server every time. The application performs the task of matching the SessionID with a database entry.

It also keeps track of the values and variables we set up in the create_session() view function.

The request object has a session attribute, and when the server executes the code, the session middleware and the session’s application operate together seamlessly.

request.session[] acts like a python dictionary data structure, allowing you to store values alongside relevant keys.

In the access_session() function, we used the get() in conjunction with request.session and gave the key’s value.

As a result, you’ll have easy access to the sessions.

There are numerous methods associated with the HttpRequest object’s session argument.

Deleting Django Sessions

You can probably remove the sessions after they have completed their tasks. Simply said, this view function should be included in the views.py file.

Code for delete_session:

def delete_session(request):
    try:
        del request.session['Emp_name']
        del request.session['Emp_Email']
    except KeyError:
        pass
    return HttpResponse("<h1>TechVidvan<br>Session Data cleared</h1>")

This code is also written in pure Python, using the concept of exception handling. We can use del to delete a session or a specific key within that session.

del request.session[‘key_name’]

To make this code work, add the following to the urlpatterns:

path('Delete_sn', views.delete_session),

Don’t worry if your cookie isn’t deleted because we just use this way to erase your data in the Django database, not the session ID and cookie.

Although sessions are deleted when the browser is closed, we use the flush() function to entirely erase session-related cookies.

Let’s have a look at Output:

Django Delete Session

Additional Actions Using Sessions

We’ve seen how to store and access a session, but it’s also worth noting that the request’s session attribute has various additional helpful actions, such as

Actions 
What does it do?
set_expiry (value):
Sets the session's expiration time.


get_expiry_age():
It returns the number of seconds till the session expires 


get_expiry_date():
It is a function that returns the date when something has expired. 


clear_expired():
Helps in removing expired sessions from the session store.


get_expire_at_browser_close():
If the user's session cookies have expired when the user's web browser is closed, this method returns True or False.

Session Timeout in Django

This is also one of the features which we can use while working with Django Sessions.

Mention the code below in settings to timeout a Django session after a specific timestamp (in seconds).
py

SESSION COOKIE AGE = 20 # for a time stamp of 20 seconds

In the settings, specify the code below to timeout a Django session after a certain amount of time (in seconds) of inactivity.

pip install django-session-timeout

MIDDLEWARE = [
    ...
    'django_session_timeout.middleware.SessionTimeoutMiddleware',
    ...
    ]
                                
    SESSION_EXPIRE_SECONDS = 20
    SESSION_EXPIRE_AFTER_LAST_ACTIVITY = True

Configuration of the Django Session Engine

Session engines can be configured in a variety of ways. It’s a crucial decision because storage solutions can improve speed and response time.

Django allows you to choose from these possibilities, but it does not limit your options. If you want to use a different storage technique, go to djangopackages.org.

1. Using a database Sessions

We’ve been using this way because we have the django.contrib.sessions application in our settings.py file’s under the INSTALLED APPS list.

This is a typical implementation that covers a lot of security flaws. It also comes with several functionalities that you can use directly with Django’s view methods and models.

2. Through the use of cached sessions

You can utilise cache-based sessions to improve the performance of your website. You can use this space to practise a variety of techniques, such as setting up multiple caches.

Django offers you additional session engines for this purpose:

django.contrib.sessions.backends.cache

Data is directly stored in the cache by the above engine.

django.contrib.sessions.backends.cache db

On the other hand, this engine is useful when you wish to use a write-through cache to save persistent sessions data with your server.

Both strategies significantly boost your performance.

3. Using File-based Sessions

You can utilise Django’s engine to store your sessions data in a file-based system.

django.contrib.sessions.backends.file

You’ll also need to make sure that your web server has permission to read and write the directory where your sessions file is stored.

4. Through the use of cookie-based sessions

We don’t recommend this one because sessions were designed to avoid storing data in cookies in the first place, but it’s still used by developers for whatever reason.

django.contrib,sessions.backends.signed cookies

With the help of Django’s cryptographic signing tool and the secret key, your session data can be saved.

It has all of the issues with cookies, the most serious of which is that session cookies are signed but not encrypted, allowing the client to access them. It also has performance difficulties because the request size is affected by the cookie size.

Summary:

Django provides some pretty intuitive methods for implementing sessions and interacting with them. It includes several choices for making your web project as dynamic and fast-paced as you want it to be.