top

Understanding how to write a custom middleware in Django

This a very basic tutorial on understanding Django-middlewares. We’ll try to understand middlewares and write one of our own. The prerequisite for this tutorial is nothing but knowing the Django application structure and understanding the requests/responses. What are Middlewares? The name sounds all fancy and stuff but it’s quite straightforward if you think about it. We’ll take an analogy and compare it with what it actually means and try to know it better. According to Docs: Middleware is a framework of hooks into Django’s request/response processing. It’s a light, low-level “plugin” system for globally altering Django’s input or output. Let’s consider a situation where you use 3 different kinds of software. For example, you use X for builds, Y for documentation and Z for development purposes. But now you want to integrate all of this into one big system to keep your software updated. If you go ahead and start doing it manually, it may take a long period of time. But somehow you come up with a framework that reads the input/output of your resources and gives an overall correct output for an input. In other words, the output generated by X can be used by Y and Z. So basically, Middleware passes data between 2 or more applications. Examples of operations performed by Middlewares: HTTP authentication Session management Encryption Validation How does Django Middleware work? It is essential to know how Django middleware process the request before going to create a custom Django middleware. The following picture shows the working of Django middlewares.                           Example of how Django middleware are processed The following block of code shows the middlewares that Django provides us. You can find these in the settings.py file of your Django application.   Django applies the above middleware order in a top-down manner. Each Middleware class is a layer that wraps the view function. When the request passes through all the layers one by one, a response is generated and it again goes through all the layers on its way back out. Writing a custom Middleware Now that you know what is a middleware and how actually it works, you can write your own Django custom middleware. For this, I’ll be showing you a very simple example of a custom middleware. Remind you that the practice followed is as per the Django documentation. In very simple terms, it is much like a view function. The only thing we need to care about is that there are 2 hooks available for request and 3 for response. Before calling the view, in the request phase, the available hooks are: process_request() process_view() After calling the view, in the response phase, the available hooks are: process_exception() process_template_response() process_response() While writing a middleware, all we need to do is define one or more of the above functions as per our need. Let’s suppose that we have a Django app that has the following models.py file. And now create a file where you define your custom middleware that uses the above model. Let’s call this file as moviemiddleware.py Now in your settings.py file, Note that the order of middlewares is very important. When you run your application, it should output the following: This was a very trivial example to let you know how exactly middleware can be used and further manipulated for our own purposes. Now let’s take a little more complicated example. In the following example, we will write a middleware that can handle redirects in the URL along with parameters. The default Django project doesn’t allow it beforehand. The logic of our middleware will be very simple: We’ll separate URL parameters from the absolute_path Next get exact `redirect_path` of separated absolute_path Then append the URL parameters which separated from absolute_path to redirect_path Since this is a response that we get in our HTTP cycle, we need to make a process_response() function in our middleware class. The layout of our CustomRedirectMiddleware.py will be - Let’s get into it and write a middleware for this. As you can see, the above code handles the three logic statements and can be used in your application by adding it to MIDDLEWARE in your settings.py file. There are a lot more cases where middlewares can be used as per the need of the application. The things to keep in mind from this tutorial are: Ordering in middlewares is very important as they are processed while an HTTP cycle. At least one of the requests/responses is necessary in order for it to be a Django middleware. Hope this article helped you to clearly understand how to set up a custom middleware in Django.  
Rated 4.0/5 based on 23 customer reviews
Normal Mode Dark Mode

Understanding how to write a custom middleware in Django

Nitin Prakash
Blog
12th Apr, 2018
Understanding how to write a custom middleware in Django

This a very basic tutorial on understanding Django-middlewares. We’ll try to understand middlewares and write one of our own. The prerequisite for this tutorial is nothing but knowing the Django application structure and understanding the requests/responses.


What are Middlewares?

The name sounds all fancy and stuff but it’s quite straightforward if you think about it. We’ll take an analogy and compare it with what it actually means and try to know it better.

According to Docs:

Middleware is a framework of hooks into Django’s request/response processing.
It’s a light, low-level “plugin” system for globally altering Django’s input or output.


Let’s consider a situation where you use 3 different kinds of software. For example, you use X for builds, Y for documentation and Z for development purposes. But now you want to integrate all of this into one big system to keep your software updated.

If you go ahead and start doing it manually, it may take a long period of time. But somehow you come up with a framework that reads the input/output of your resources and gives an overall correct output for an input.

In other words, the output generated by X can be used by Y and Z.
So basically, Middleware passes data between 2 or more applications.

Examples of operations performed by Middlewares:

  • HTTP authentication
  • Session management
  • Encryption
  • Validation


How does Django Middleware work?

It is essential to know how Django middleware process the request before going to create a custom Django middleware.
The following picture shows the working of Django middlewares.
 

Django middleware are processed
                        Example of how Django middleware are processed

The following block of code shows the middlewares that Django provides us. You can find these in the settings.py file of your Django application.
 

Django applies the above middleware order in a top-down manner. Each Middleware class is a layer that wraps the view function. When the request passes through all the layers one by one, a response is generated and it again goes through all the layers on its way back out.


Writing a custom Middleware

Now that you know what is a middleware and how actually it works, you can write your own Django custom middleware. For this, I’ll be showing you a very simple example of a custom middleware.

Remind you that the practice followed is as per the Django documentation.

In very simple terms, it is much like a view function.
The only thing we need to care about is that there are 2 hooks available for request and 3 for response.

Before calling the view, in the request phase, the available hooks are:

  • process_request()
  • process_view()

After calling the view, in the response phase, the available hooks are:

  • process_exception()
  • process_template_response()
  • process_response()

While writing a middleware, all we need to do is define one or more of the above functions as per our need.
Let’s suppose that we have a Django app that has the following models.py file.

And now create a file where you define your custom middleware that uses the above model. Let’s call this file as moviemiddleware.py

Now in your settings.py file,

Note that the order of middlewares is very important. When you run your application, it should output the following:

This was a very trivial example to let you know how exactly middleware can be used and further manipulated for our own purposes. Now let’s take a little more complicated example. In the following example, we will write a middleware that can handle redirects in the URL along with parameters. The default Django project doesn’t allow it beforehand.

The logic of our middleware will be very simple:

  • We’ll separate URL parameters from the absolute_path
  • Next get exact `redirect_path` of separated absolute_path
  • Then append the URL parameters which separated from absolute_path to redirect_path

Since this is a response that we get in our HTTP cycle, we need to make a process_response() function in our middleware class.

The layout of our CustomRedirectMiddleware.py will be -

Let’s get into it and write a middleware for this.

As you can see, the above code handles the three logic statements and can be used in your application by adding it to MIDDLEWARE in your settings.py file.
There are a lot more cases where middlewares can be used as per the need of the application. The things to keep in mind from this tutorial are:

  • Ordering in middlewares is very important as they are processed while an HTTP cycle.
  • At least one of the requests/responses is necessary in order for it to be a Django middleware.

Hope this article helped you to clearly understand how to set up a custom middleware in Django.
 

Nitin

Nitin Prakash

Blog Author

I'm a software engineering student. I like to code in C++ and Python. I'm a freelancer and like to build web applications and softwares. Always looking forward to writing better codes.

Leave a Reply

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

SUBSCRIBE OUR BLOG

Follow Us On

Share on

other Blogs

20% Discount