murtaza52
murtaza52

Reputation: 47451

how to define a custom wsgi middleware for django

I want to write a custom wsgi middleware, which is called on every incoming request. It checks the url, and if the user is authenticated and allows the request to proceed or rejects it.

What is the best way to add wsgi middleware in django ?

Upvotes: 3

Views: 1067

Answers (2)

Akshar Raaj
Akshar Raaj

Reputation: 15241

You do not need a wsgi middleware here and can easily use django middleware.

some_app/middleware.py

from django.http import HttpResponseForbidden

class AuthenticateMiddleware(object):

    def process_request(self, request):
        #do something with request.path
        if request.user.is_authenticated():
            #can do something or just pass
            #but do not return a response from here
        else:
            #return a response from here so that view doesn't get called
            return HttpResponseForbidden()

process_request() of any middleware is called before the view is processed. If you return an instance of HttpResponse from this method then the view will not be called. Since HttpResponseForbidden is a subclass of HttpResponse, so the view will not be called if the user is not authenticated.

You need to add this custom middleware to MIDDLEWARE_CLASSES.

settings.py

MIDDLEWARE_CLASSES = ( 
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'some_app.middleware.AuthenticationMiddleware',
)

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 600059

Why do you want to do this as a WSGI middleware, specifically? Django doesn't operate particularly well with those - there was some work a few years ago to try and harmonize Django middleware with WSGI middleware, but it didn't really get anywhere.

Django has its own version of middleware, which is very well documented, and your request could be done in about three lines.

Upvotes: 1

Related Questions