1.14.1.3 Callables, Classes or Functions?

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.

You can also specify your application object as a class. Consider this example

def myApp(environ, start_response):
    start_response('200 OK', [('Content-type','text/plain')])
    return ['Hello World!']
    
application = myApp

The following code performs exactly the same task.

class MyApp(web.wsgi.base.BaseApplication):
    def __call__(self, environ, start_response):
        start_response('200 OK', [('Content-type','text/plain')])
        return ['Hello World!']

application = MyApp()

It can also be useful to specify applications as classes so that functionality can be derived from other applications.