The Handler Base

Step 1: The Handler Base

A middleware pipeline is a linked chain of handlers. Each handler does its bit of work and then either passes the request along to the next handler or stops the chain. The base class holds that plumbing so concrete handlers only worry about their own logic.

Implement the default handle behavior on Handler:

  • init already sets self._next to None (no next handler yet).
  • set_next(handler) already stores the next handler and returns it, so you can chain calls like a.set_next(b).set_next(c).
  • handle(request) is the default: if there is a next handler, delegate to it and return its result; otherwise return None. Concrete handlers will override this and call super().handle(request) to pass down the chain.
Hints
Starter code
class Handler:
    def __init__(self):
        self._next = None

    def set_next(self, handler):
        self._next = handler
        return handler

    def handle(self, request):
        """Default behavior: pass the request to the next handler, or return None."""
        # TODO: if self._next is not None: return self._next.handle(request)
        # TODO: return None
        pass
Write it on a laptop

The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.