I have been quite careful all the way through the introduction to describe the application and middleware as callables and not just as functions (which is what they have happened to be so far). We could re-write the session middleware component described in the previous section as follows:
class Session: def __init__(self, application): self.application = application def __call__(self, environ, start_response): if "superSession" not in environ: import superSession environ["superSession"] = superSession.session() # Options would obviously need specifying return self.application(environ,start_response) application = Session(exampleApplication)
If you think carefully about what is happening here you will realise that our Session
class behaves in exactly the same way as the function session did in the previous example.
The advantage of using a class rather than a function for a middleware component is that you can derive another middleware component from an existing one that provides similar functionality without re-writing the entire component.
The web.wsgi module contains middleware classes for all of the web modules functionality which you can use on their own or as base classes for your own middleware components including session functionality. The middleware components are all described later on in this documentation.