Async Web Framework: Middleware Onion Pipeline
Middlewares wrap application handlers in concentric layers (the "onion" pattern). Inbound requests pass inward through pre-processing hooks, hit the core handler, and outbound responses travel backward through post-processing hooks 🧅.
import asyncio
log = []
async def core_handler(req):
log.append("core")
return "200 OK"
def middleware(next_handler, label):
async def wrapped(req):
log.append(f"{label}_in")
res = await next_handler(req)
log.append(f"{label}_out")
return res
return wrapped
app = middleware(middleware(core_handler, "auth"), "timer")
asyncio.run(app({"path": "/"}))
print(f"Execution Order: {log} 🧅")
# 115. Async Web Framework: Middleware Onion Pipeline Middlewares wrap application handlers in concentric layers (the "onion" pattern). Inbound requests pass inward through pre-processing hooks, hit the core handler, and outbound responses travel backward through post-processing hooks 🧅. ```python import asyncio log = [] async def core_handler(req): log.append("core") return "200 OK" def middleware(next_handler, label): async def wrapped(req): log.append(f"{label}_in") res = await next_handler(req) log.append(f"{label}_out") return res return wrapped app = middleware(middleware(core_handler, "auth"), "timer") asyncio.run(app({"path": "/"})) print(f"Execution Order: {log} 🧅") ``` If an authentication middleware detects an invalid JWT or rate-limit violation on the inbound pass, it can short-circuit immediately: returning an early 401 response without ever invoking inner handlers 🛡️! --- ### Question Why is middleware call flow described as an 'onion' pipeline in web framework design? 🧠 - [ ] a. Outer middleware executes first on inbound requests, and last in reverse sequence on outbound responses 🧅 - [ ] b. It routes network packets through encrypted Tor onion circuits - [ ] c. It compresses JSON responses into binary multi-layer payloads - [ ] d. It restricts application routes to a maximum of 3 handler layers --- ### Challenge Build an onion pipeline where `core` appends `'core'` to `log`, wrapped by `timer` logging `'timer_in'` and `'timer_out'`. Run and print `log`. 🎯 <details> <summary>Solution</summary> ```python import asyncio log = [] async def core(): log.append('core') def timer_mw(next_fn): async def wrapped(): log.append('timer_in') await next_fn() log.append('timer_out') return wrapped asyncio.run(timer_mw(core)()) print(log) ``` </details>