What’s Middleware?

A middleware component is simply a Python class that conforms to a certain API. Before diving into the formal aspects of what that API is, let’s look at a very simple example.

High-traffic sites often need to deploy Django behind a load-balancing proxy. This can cause a few small complications, one of which is that every request’s remote IP (request.META[“REMOTE_IP”]) will be that of the load balancer, not the actual IP making the request. Load balancers deal with this by setting a special header, X-Forwarded-For, to the actual requesting IP address. So here’s a small bit of middleware that lets sites running behind a proxy still see the correct IP address in request.META[“REMOTE_ADDR”]:

class SetRemoteAddrFromForwardedFor(object):
def process_request(self, request):
try:
real_ip = request.META[‘HTTP_X_FORWARDED_FOR’] except KeyError:
pass
else:
# HTTP_X_FORWARDED_FOR can be a comma-separated list of IPs.
# Take just the first one.
real_ip = real_ip.split(“,”)[0] request.META[‘REMOTE_ADDR’] = real_ip

If this is installed, every request’s X-Forwarded-For value will be automatically inserted into request.META[‘REMOTE_ADDR’]. This means your Django applications don’t need to be concerned with whether they’re behind a load-balancing proxy or not; they can simply access request.META[‘REMOTE_ADDR’], and that will work whether or not a proxy is being used. In fact, this is a common enough need that this piece of middleware is a built-in part of Django. It lives in django.middleware.http, and you can read a bit more about it in the next section.

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. For example, Django includes a middleware component, AuthenticationMiddleware, that associates users with requests using sessions.

This document explains how middleware works, how you activate middleware, and how to write your own middleware. Django ships with some built-in middleware you can use right out of the box.

Back to Tutorial

Middleware
Middleware Installation

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?