Learn middleware by making auto exception googling middleware

Posted by Afsal on 07-Jan-2022

Today, we are going to make a middleware that searches for a solution in google when an Exception is raised. Middleware is the layer that lies between request and response in Django. Django provides so many defaults like AuthenticationMiddleware, SecurityMiddleware, CsrfViewMiddleware etc. The list of enabled middlewares are listed in a setting called MIDDLEWARE in the settings.py file

Example:

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

The order of execution is done from the top to the bottom in this list.

Our plan is to create a middleware that searches solutions in google whenever there is an exception in the code.

Middleware is a simple python class. It provides us with some hooks in which we can write our own logic. They are given below.

__init__ : This will be triggered only once when the server is starting. Hence, do not use this as other hooks.

__call__ : Whenever a request is initiated, this will get triggered.

process_view: This will be triggered just before a view start processing 

process_exception: When an exception occurs it will be triggered

process_template_response: This will be triggered just after template rendering

You can refer to Django's official documentation for more details. 

For our case, we are using the process_exception hook. Our code will look like this:

I have created a middleware.py in testapp and my code look like this

from django.http import HttpResponseRedirect
from django.conf import settings

class SearchGoogleMiddleWare:
    def process_exception(self, request, exception):
        if settings.DEBUG:
            url = f"http://www.google.com/search?q={exception.__class__.__name__}"
            return HttpResponseRedirect(url)

 

In this example whenever there is an exception and the app is in debug mode, the hook will be triggered and it will automatically redirect us to google explaining the error.

Once the middleware is completed, add it to our settings.Full path to the middleware should be added. For my case, the path will be testapp.middleware.SearchGoogleMiddleWare

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'testapp.middleware.SearchGoogleMiddleWare'
]

To test this, I have added a view but the template provided in the view does not exist. When I access the view, a “not found exception” template is shown. At that time our middleware will search the not found error message template in google and will redirect us to that page.

Hope you have learned from this post. Please share your valuable suggestion or new topic to email afsal@parseltongue.co.in