0
0
FastAPIframework~10 mins

Background tasks 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 BackgroundTasks class from FastAPI.

FastAPI
from fastapi import [1]
Drag options to blanks, or click blank then click option'
ARequest
BBackgroundTasks
CDepends
DFastAPI
Attempts:
3 left
💡 Hint
Common Mistakes
Importing the main FastAPI class instead of BackgroundTasks.
Importing unrelated classes like Request or Depends.
2fill in blank
medium

Complete the function parameter to accept background tasks in a FastAPI endpoint.

FastAPI
from fastapi import BackgroundTasks

@app.post("/send")
async def send_email(background_tasks: [1]):
    pass
Drag options to blanks, or click blank then click option'
ABackgroundTasks
BRequest
CDepends
DResponse
Attempts:
3 left
💡 Hint
Common Mistakes
Using Request or Response instead of BackgroundTasks.
Forgetting to type the parameter as BackgroundTasks.
3fill in blank
hard

Fix the error in scheduling a background task to call the function write_log with argument message.

FastAPI
def write_log(message: str):
    with open("log.txt", "a") as log:
        log.write(message + "\n")

@app.post("/log")
async def log_message(background_tasks: BackgroundTasks, message: str):
    background_tasks.[1](write_log, message)
    return {"message": "Log scheduled"}
Drag options to blanks, or click blank then click option'
Arun_task
Badd_background
Cschedule_task
Dadd_task
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect method names like add_background or run_task.
Forgetting to call the method on background_tasks.
4fill in blank
hard

Fill both blanks to create a background task that writes a message and returns a confirmation.

FastAPI
def save_data(data: str):
    with open("data.txt", "a") as file:
        file.write(data + "\n")

@app.post("/save")
async def save_endpoint([1]: BackgroundTasks, data: str):
    [2].add_task(save_data, data)
    return {"status": "Data saved in background"}
Drag options to blanks, or click blank then click option'
Abackground_tasks
Brequest
Ctasks
Dbg
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names for parameter and method call.
Using unrelated names like request or tasks.
5fill in blank
hard

Fill all three blanks to define a background task function, add it in the endpoint, and return a success message.

FastAPI
def [1](email: str):
    print(f"Sending email to {email}")

@app.post("/email")
async def send(email: str, [2]: BackgroundTasks):
    [2].add_task([1], email)
    return {"detail": "Email will be sent"}
Drag options to blanks, or click blank then click option'
Asend_email
Bbackground_tasks
Dsend_task
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for the function and task call.
Using wrong parameter names for background tasks.