How to create a custom Middleware



Django Middleware is very important, it's executed each time a connection appear in any direction, client to server or server to client, and can be very useful in different situations.

If we're interested we can check the official documentation from Django Docs: Middleware if we like to have a deeper understanding about how it works.

On this example we're going to do a middleware that gives access or deny access to some IP addresses.

To create our custom middleware we have to create a new folder with name 'middleware' at the same path as 'template' folder, or views.py, urls.py etc... (Path: myproject/myproject/middleware)

To make Django realize that we added this new folder 'middleware' to our project we need to create an empty file inside the folder with the name __init__.py

So, now we've created and initialized the folder middleware, now is turn to create our custom middleware, so we craete a new file inside the 'middleware' folder with the namme filter_ip_middleware.py, and we add this code inside:

 

filter_ip_middleware.py

class FilterIPMiddleware(object):
    # Check if client IP is allowed
    def process_request(self, request):
        allowed_ips = ['192.168.1.1', '123.123.123.123']  # This is the list of allowed IP's
        ip = request.META.get('REMOTE_ADDR')  # Get client IP
        if ip not in allowed_ips:           
           raise Http403  # Here we generate error "forbidden site"
 
        # If the IP is allowed we don't do anything
        return None

The last step is look inside settings.py for the line MIDDLEWARE_CLASSES and add at the end of it our custom middleware, it should be something like:

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # Above middlewares are configured by default 
    # Next we write our middleware
    'myproject.middleware.filter_ip_middleware.FilterIPMiddleware'
)

'myproject.middleware.filter_ip_middleware.FilterIPMiddleware':
    - 'myproject': This should be our project name
    - 'middleware': This refers to the folder where our custom middleware is
    - 'filter_ip_middleware': This refers to the file that contains our middleware
    - 'FilterIPMiddleware': This refers to the name of the class for our custom middleware

Any doubt don't hesitate to comment!!

Leave a comment

You have to wait to comment again. Wait Time: