0
0
FastAPIframework~10 mins

Lifespan context manager in FastAPI - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the asynccontextmanager decorator used for lifespan from contextlib.

FastAPI
from contextlib import [1]
Drag options to blanks, or click blank then click option'
AFastAPI
Basynccontextmanager
CRequest
DDepends
Attempts:
3 left
💡 Hint
Common Mistakes
Importing FastAPI instead of asynccontextmanager
Importing unrelated classes like Request or Depends
2fill in blank
medium

Complete the code to define an async lifespan context manager function named 'lifespan'.

FastAPI
@asynccontextmanager
async def [1]():
    print('Starting app')
    yield
    print('Shutting down app')
Drag options to blanks, or click blank then click option'
Ashutdown
Bapp
Cstartup
Dlifespan
Attempts:
3 left
💡 Hint
Common Mistakes
Naming the function differently than lifespan
Forgetting to use yield inside the function
3fill in blank
hard

Fix the error in the code to create a FastAPI app using the lifespan context manager.

FastAPI
app = FastAPI(lifespan=[1])
Drag options to blanks, or click blank then click option'
Alifespan
Blifespan()
Clifespan_manager
Dlifespan_context
Attempts:
3 left
💡 Hint
Common Mistakes
Calling the lifespan function instead of passing it
Passing a wrong variable name
4fill in blank
hard

Fill both blanks to correctly use the lifespan context manager with async code.

FastAPI
from contextlib import [1]

@[2]
async def lifespan():
    print('App starting')
    yield
    print('App shutting down')
Drag options to blanks, or click blank then click option'
Aasynccontextmanager
Blifespan
Ccontextmanager
Dapp
Attempts:
3 left
💡 Hint
Common Mistakes
Using synchronous contextmanager instead of asynccontextmanager
Using wrong decorator name
5fill in blank
hard

Fill all three blanks to create a FastAPI app with a lifespan context manager that prints messages on startup and shutdown.

FastAPI
from contextlib import [1]
from fastapi import FastAPI

@[2]
async def lifespan():
    print('Starting')
    yield
    print('Stopping')

app = FastAPI([3]=lifespan)
Drag options to blanks, or click blank then click option'
Aasynccontextmanager
Clifespan
Dstartup
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'startup' instead of 'lifespan' as argument
Not importing asynccontextmanager
Not decorating the function properly