Wednesday, September 9, 2015

What Is Middleware In Django ?



                 What Is Middleware In Django ?



Common Question for Python Django Developer Interviews ? Actually what is Middleware ? What is Role ? How many middleware are there ? can we write own middlewares in a application if yes tell me how ?

Haaahha Now you  also Confused how to answer these questions ?  , when i enter to interview panel i sucked lot of times  , i make it my own ways ..

These are the questions commonly asking for the Interviews , Middleware have main role in our django application so only they asking these questions to everyone. Here I 'm telling you how you can easily tackle with these questions.

What is Middleware ? 

    Middleware is a Middleware is a ................, Dont worry i will help you out , 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. Each middleware component is responsible for doing some specific function.

What are the Common Middleware Classes in Django ? 

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

if you need more details about the each of the middleware classes please follow the link 

How to Write Own Middlewares in our project ?

Step 1 :

   if you don't have it you need to create the middleware folder within your app following the Structre.

yourapp/yourapp/middleware

The folder middleware should be placed in the same folder as settings.py , urls , templates
Important : Don't forget to create the __init__.py empty file inside the middleware folder so your app recognize this folder. 

Step 2 :

Create Middleware.

    Now we should create a file for our custon middleware, in this blog let's suppose we want a middleware that filter users based on their IP. we create file called filter_ip_middleware.py the middleware folder with this code

class FilterIPMiddleware(object):
    # Check if client IP is allowed
    def process_request(self, request):
        allowed_ips = ['192.168.1.1', '123.123.123.123', etc...] # Authorized ip's
        ip = request.META.get('REMOTE_ADDR') # Get client IP
        if ip not in allowed_ips:
            raise Http403 # If user is not allowed raise Error

       # If IP is allowed we don't do anything
       return None

Step 3 :

Add the midleware in your 'settings.py' .

   We need to look for the MIDDLEWARE_CLASSES inside the settings.py and there we need to add our middleware( Add it in the last position ) . It should be 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 are django standard middlewares

     # Now we add here our custom middleware
     'yourapp.middleware.filter_ip_middleware.FilterIPMiddleware'
)

Step 4 :

DONE ! Now every request from the every client will call your custom middleware and process your
custom code. !


                                                         THANK YOU

1 comment:

  1. Salaam,


    Hip Hip Hooray! I was always told that slightly slow in the head, a slow learner. Not anymore! It’s like you have my back. I can’t tell you how much I’ve learnt here and how easily! Thank you for blessing me with this effortlessly ingestible digestible content.


    I'm new to python and trying to make a basic tree, I have made this code to draw the triangles on top of each other but I am unable to work out how to make them larger as they go down. Can any one help?
    Python Code: (Double-click to select all)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13 number_of_shapes = 3
    for shape in range(1, number_of_shapes + 1):
    # Draw a Triangle
    for sides in range(1, 4):
    forward(60)
    left(120)
    # Move forward to start position of next triangle
    penup()
    right(120)
    forward(60)
    left(120)
    forward(30)
    pendown()

    It was cool to see your article pop up in my google search for the process yesterday. Great Guide.
    Keep up the good work!


    Best Regards,

    ReplyDelete