Bird
0
0

Identify the error in this middleware code: ```python class TimingMiddleware(BaseHTTPMiddleware): async def dispatch(self, request, call_next): start = time.time() response = call_next(request) duration = time.time() - start response.headers["X-Process-Time"] = str(duration) return response ```

medium📝 Debug Q6 of 15
FastAPI - Middleware and Hooks
Identify the error in this middleware code: ```python class TimingMiddleware(BaseHTTPMiddleware): async def dispatch(self, request, call_next): start = time.time() response = call_next(request) duration = time.time() - start response.headers["X-Process-Time"] = str(duration) return response ```
Adispatch method should not be async
BMissing await before call_next(request)
CHeaders cannot be modified in middleware
Dtime.time() is not imported
Step-by-Step Solution
Solution:
  1. Step 1: Check call_next usage

    call_next is an async function and must be awaited to get the response.
  2. Step 2: Identify missing await

    The code calls call_next(request) without await, causing a coroutine object instead of response.
  3. Final Answer:

    Missing await before call_next(request) -> Option B
  4. Quick Check:

    Await call_next to get response [OK]
Quick Trick: Always await async call_next(request) in dispatch [OK]
Common Mistakes:
MISTAKES
  • Forgetting await on call_next
  • Assuming headers can't be changed
  • Thinking dispatch can't be async

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes