Middleware

On occasion, you’ll need to run a piece of code on each and every request that Django handles. This code might need to modify the request before the view handles it, it might need to log information about the request for debugging purposes, and so forth. You can do this with Django’s middleware framework, which is a set of hooks into Django’s request/response processing. It’s a light, low-level “plug-in” system capable of globally altering both Django’s input and output.

Each middleware component is responsible for doing some specific function. If you’re reading this book linearly (sorry, postmodernists), you’ve seen middleware a number of times already:

  • All of the session and user tools that we looked at in Chapter 12 are made possible by a few small pieces of middleware (more specifically, the middleware makes session and request.user available to you in views).
  • The sitewide cache discussed in Chapter 13 is actually just a piece of middleware that bypasses the call to your view function if the response for that view has already been cached.
  • The flatpages, redirects, and csrf contributed applications from Chapter 14 all do their magic through middleware components.

This chapter dives deeper into exactly what middleware is and how it works, and explains how you can write your own middleware.

Back to Tutorial

Share this post
[social_warfare]
Introduction to APR
What’s Middleware?

Get industry recognized certification – Contact us

keyboard_arrow_up