Why Django Middleware is so darn cool
Django is great for a bunch of reasons, one of the coolest is the built in middleware for security, sessions and a bunch of other nifty stuff. The cool stuff happens when you write your own Django middleware.
Django processes requests in a very logical order
And it’s even cooler when you add your own layer in there, and it’s not even that hard (even though the docs make it looks complicated). I made a pretty nifty one to log requests/responses.
class RequestLogging(object):
def process_request(self, request):
'''
Log the meta data of an incoming request '''
meta_data = request.__dict__.get('META')
print(meta_data)
def process_response(self, request, response):
'''
Log the outgoing response '''
print(response)
return response
And that’s all there is. The only thing left to do is hook it up in the middleware in the settings.
MIDDLEWARE_CLASSES = [
‘django.middleware.security.SecurityMiddleware’,
‘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’,
‘myApp.LoggingMiddleware.RequestLogging’,
#LoggingMiddleware is the name of the file RequestLogging is in
]
If you want to add some logic to validate sessions, or append a response id to your data then you can easily and simply add that to your middleware. There’s no limit to the cool stuff you can do.