All about Django Middleware

Priyank Desai
Towards Dev
Published in
4 min readApr 23, 2024

--

A great way to keep an eye on your view request.

We will focus on some of the important aspects of Django Middleware.

  • What is Middleware?
  • How does is work?
  • How many type of Middleware are there?
  • When to use Middleware?
  • Working Example with code.

What is Django middleware?

Middleware in Django is a powerful tool that allows you to modify the request/response cycle globally. It’s like a gatekeeper standing between your Django application and the outside world, intercepting requests as they come in and responses as they go out.

It’s a modular component that helps you handle cross-cutting concerns such as authentication, security, logging, and more.

How does it work?

Middleware works by sitting in the middle of the request-response cycle. When a request comes into your Django application, it passes through each middleware component in the defined order.

Each middleware can inspect, modify, or even short-circuit the request before passing it on to the next middleware or view.

Similarly, when the response is generated, it passes back through the middleware in the reverse order, allowing each middleware to inspect or modify the response.

How many types of Middleware are there?

  • Built-in Middleware: These are provided by Django out of the box, handling tasks like session management, authentication, CSRF protection, etc.
  • Custom Middleware: You can create your own middleware to address specific needs of your application, like adding custom headers, modifying requests/responses, or implementing custom logic.
  • Third-party Middleware: There are also middleware packages developed by the Django community to handle various functionalities like caching, compression, CORS, etc.

To check existing Middleware in your Django project. Open setting.py and go to middleware section.

When to use Middleware?

Middleware should be used when you need to apply a certain behavior or modification across multiple views or requests/responses in your Django application. Some common scenarios where middleware can be useful include:

  • Authentication: Enforcing user authentication globally across your application.
  • Logging: Capturing request/response data for debugging or analytics purposes.
  • Security: Implementing security measures like CSRF protection, XSS prevention, etc.
  • Customization: Adding custom headers, modifying request/response objects, or implementing custom logic that needs to be applied across multiple views.

Essentially, if there’s a task that needs to be performed for every request or response, or if you need to encapsulate a specific behavior that spans multiple views, middleware is likely the right tool for the job.

Working Example with code.

Setup Django Project

Let’s start with setting up our python environment.

pip install virtualenv
virtualenv MyFirstApp
MyFirstApp\scripts\activate

Once done, Create a new Django Project.

django-admin startproject djangoMiddleware

Now create a new App inside the Django Project.

cd djangoMiddleware
django-admin startapp mainApp

Add the App name in settings.py

INSTALLED_APPS = [
...
'mainApp',
...
]

New step is to create Middleware for the project. To do that, create a new Folder called ‘Middleware’ inside your project.

Now to create middleware we will create two files, one for Class-based middleware and another for Function-based middleware.

  • Class-based Middleware: Think of class-based middleware as a versatile toolbox. Each tool (method) inside the toolbox handles a specific job in the request-response cycle, from opening the box (__init__) to handling requests (process_request), views (process_view), exceptions (process_exception), and finally, closing the box (process_response). It's like having a Swiss Army knife for managing different aspects of your application's middleware needs.
  • Function-based Middleware: Function-based middleware is like a straightforward conveyor belt. Requests come in at one end, get processed by the function, and responses come out the other end. It’s simple, efficient, and perfect for tasks that don’t require fancy tools or complicated setups. Just feed it a request, and it handles the rest with ease.

Lastly, Open setting.py and add the newly created Middleware in it.

MIDDLEWARE = [
...
'Middleware.classbase_middleware.DemoMiddleware',
'Middleware.functionbase_middleware.simple_middleware'
...
]

Now run the project using the following command and visit this link http://127.0.0.1:8000/.

python manage.py runserver

Finally, Check the Terminal. It will show the print results.

Conclusion

In summary, middleware in Django acts as a crucial intermediary, managing the flow of requests and responses in web applications. Whether in the form of class-based or function-based middleware, its role is to enhance functionality, security, and performance. By leveraging middleware effectively, developers can streamline development and ensure the smooth operation of Django applications.

Source code: (https://github.com/Priyank010/DjangoMiddleware)

--

--