Bird
0
0

Consider this FastAPI lifespan function:

medium📝 component behavior Q4 of 15
FastAPI - Middleware and Hooks
Consider this FastAPI lifespan function:
async def lifespan(app: FastAPI):
    print('App is starting')
    yield
    print('App is stopping')

What output will appear when the app starts and then shuts down?
APrints 'App is starting' on startup and 'App is stopping' on shutdown
BPrints both messages immediately on startup
CPrints 'App is stopping' before 'App is starting'
DNo output is printed because yield stops execution
Step-by-Step Solution
Solution:
  1. Step 1: Analyze lifespan function

    Code prints before yield on startup, after yield on shutdown.
  2. Step 2: Execution order

    On app start: 'App is starting' prints; on shutdown: 'App is stopping' prints.
  3. Final Answer:

    Prints 'App is starting' on startup and 'App is stopping' on shutdown -> Option A
  4. Quick Check:

    Yield separates startup and shutdown phases [OK]
Quick Trick: Code before yield runs on startup, after yield on shutdown [OK]
Common Mistakes:
MISTAKES
  • Assuming yield stops all output
  • Thinking both prints happen at startup

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes