Complete the code to import the BackgroundTasks class from FastAPI.
from fastapi import [1]
The BackgroundTasks class is imported from FastAPI to schedule background work.
Complete the function parameter to accept background tasks in a FastAPI endpoint.
from fastapi import BackgroundTasks @app.post("/send") async def send_email(background_tasks: [1]): pass
The endpoint function must accept a parameter of type BackgroundTasks to schedule background work.
Fix the error in scheduling a background task to call the function write_log with argument message.
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"}
The method to add a background task is add_task. Other names are incorrect and cause errors.
Fill both blanks to create a background task that writes a message and returns a confirmation.
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"}
The parameter name is usually background_tasks, and the same variable is used to call add_task.
Fill all three blanks to define a background task function, add it in the endpoint, and return a success message.
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"}
The function name is send_email. The parameter for background tasks is background_tasks. The same function name is used when adding the task.