Bird
0
0

You want to create a middleware that adds a custom header 'X-Process-Time' showing how long the request took. Which code snippet correctly implements this?

hard📝 state output Q15 of 15
FastAPI - Middleware and Hooks
You want to create a middleware that adds a custom header 'X-Process-Time' showing how long the request took. Which code snippet correctly implements this?
Aclass TimerMiddleware: async 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
Bclass TimerMiddleware: async def dispatch(self, request): start = time.time() response = await call_next(request) response.headers['X-Process-Time'] = str(time.time() - start) return response
Cclass TimerMiddleware: def dispatch(self, request, call_next): start = time.time() response = call_next(request) response.headers['X-Process-Time'] = str(time.time() - start) return response
Dclass TimerMiddleware: async def dispatch(self, request, call_next): response = await call_next(request) response.headers['X-Process-Time'] = time.time() return response
Step-by-Step Solution
Solution:
  1. Step 1: Check dispatch method signature and async usage

    dispatch must be async and accept request and call_next parameters.
  2. Step 2: Verify timing and header addition

    Start time before await call_next, calculate duration after, add header as string.
  3. Step 3: Identify correct code snippet

    class TimerMiddleware: async 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 correctly implements timing, async, and header addition.
  4. Final Answer:

    The code snippet that correctly adds X-Process-Time header -> Option A
  5. Quick Check:

    Async dispatch with timing and header = A [OK]
Quick Trick: Measure time before and after await call_next, add header [OK]
Common Mistakes:
MISTAKES
  • Missing call_next parameter
  • Not awaiting call_next
  • Adding header before timing calculation
  • Using synchronous dispatch method

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes