Back
+15 XP
Concept

Chain of Responsibility: Middleware Pipelines

The Chain of Responsibility passes requests along a sequence of handlers. Each handler can inspect, transform, or abort the request before passing it to the next step 🔗.

python
class Pipeline:
    def __init__(self):
        self.middlewares = []

    def use(self, middleware):
        self.middlewares.append(middleware)

    def process(self, request):
        for mw in self.middlewares:
            request = mw(request)
        return request

pipeline = Pipeline()
pipeline.use(lambda req: req.strip())
pipeline.use(lambda req: req.lower())
pipeline.use(lambda req: f"[{req}]")

print(pipeline.process("   ADMIN_TOKEN   "))  # '[admin_token]' 🔗

# 120. Chain of Responsibility: Middleware Pipelines The Chain of Responsibility passes requests along a sequence of handlers. Each handler can inspect, transform, or abort the request before passing it to the next step 🔗. ```python class Pipeline: def __init__(self): self.middlewares = [] def use(self, middleware): self.middlewares.append(middleware) def process(self, request): for mw in self.middlewares: request = mw(request) return request pipeline = Pipeline() pipeline.use(lambda req: req.strip()) pipeline.use(lambda req: req.lower()) pipeline.use(lambda req: f"[{req}]") print(pipeline.process(" ADMIN_TOKEN ")) # '[admin_token]' 🔗 ``` This pattern is the foundational architecture behind modern web frameworks (FastAPI, Express, Django middleware, Redux middleware pipelines)! 🔗 --- ### Question Which ubiquitous web framework concept is a direct implementation of the Chain of Responsibility pattern? 🧠 - [ ] a. HTTP Middleware pipelines (authentication, CORS, rate-limiting) 🔗 - [ ] b. Database foreign key constraints - [ ] c. HTML templating engines - [ ] d. CSS grid flexbox layouts --- ### Challenge Write class `TextPipeline` with list `self.steps = []`. Add `add(self, fn)` and `run(self, text)` executing each function sequentially on `text`. Add `lambda t: t.strip()` and `lambda t: t.upper()`. Run with `' python '` and print result. 🎯 <details> <summary>Solution</summary> ```python class TextPipeline: def __init__(self): self.steps = [] def add(self, fn): self.steps.append(fn) def run(self, text): for step in self.steps: text = step(text) return text pipe = TextPipeline() pipe.add(lambda t: t.strip()) pipe.add(lambda t: t.upper()) print(pipe.run(" python ")) ``` </details>

Checkpoint

Which ubiquitous web framework concept is a direct implementation of the Chain of Responsibility pattern? 🧠

Practice

Write class `TextPipeline` with list `self.steps = []`. Add `add(self, fn)` and `run(self, text)` executing each function sequentially on `text`. Add `lambda t: t.strip()` and `lambda t: t.upper()`. Run with `' python '` and print result. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks