Bird
0
0

What is wrong with this FastAPI TrustedHostMiddleware usage?

medium📝 Debug Q7 of 15
FastAPI - Middleware and Hooks
What is wrong with this FastAPI TrustedHostMiddleware usage? ```python app.add_middleware(TrustedHostMiddleware, allowed_hosts=['example.com']) app.add_middleware(TrustedHostMiddleware, allowed_hosts=['localhost']) ```
AAdding TrustedHostMiddleware twice causes multiple independent checks to apply
Ballowed_hosts must be a single string, not list
CMiddleware cannot be added after route definitions
Dallowed_hosts parameter name is incorrect
Step-by-Step Solution
Solution:
  1. Step 1: Understand middleware stacking in FastAPI

    Adding the same middleware twice stacks separate instances, each with its own allowed_hosts list.
  2. Step 2: Analyze the effect on trusted hosts

    The request must pass all checks (host in both lists). Here, no overlap, so effectively blocks all; lists do not merge.
  3. Final Answer:

    Adding TrustedHostMiddleware twice causes multiple independent checks to apply -> Option A
  4. Quick Check:

    Multiple TrustedHostMiddleware calls stack independent checks = C [OK]
Quick Trick: Add TrustedHostMiddleware once with all hosts in list [OK]
Common Mistakes:
MISTAKES
  • Adding middleware multiple times expecting merge
  • Wrong parameter type
  • Adding middleware after routes

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes