Bird
0
0

Examine this middleware code snippet and identify the issue:

medium📝 Debug Q6 of 15
FastAPI - Middleware and Hooks
Examine this middleware code snippet and identify the issue:
class TimingMiddleware(BaseHTTPMiddleware):
    def dispatch(self, request, call_next):
        start = time.time()
        response = await call_next(request)
        process_time = time.time() - start
        response.headers['X-Process-Time'] = str(process_time)
        return response
AThe dispatch method must be declared async to use await
BThe response headers cannot be modified inside middleware
Ccall_next should not be awaited in dispatch
Dtime module cannot be used inside middleware
Step-by-Step Solution
Solution:
  1. Step 1: Check method signature

    Since dispatch uses await, it must be declared async.
  2. Step 2: Validate other statements

    Modifying response headers is allowed; call_next must be awaited; time module usage is valid.
  3. Final Answer:

    The dispatch method must be declared async to use await -> Option A
  4. Quick Check:

    Async required when using await [OK]
Quick Trick: Use async def when awaiting inside dispatch [OK]
Common Mistakes:
MISTAKES
  • Forgetting to declare dispatch as async
  • Assuming response headers are immutable
  • Not awaiting call_next leading to errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes