Consider this FastAPI endpoint using BackgroundTasks. What is the behavior of the background task?
from fastapi import FastAPI, BackgroundTasks app = FastAPI() def write_log(message: str): with open("log.txt", "a") as f: f.write(message + "\n") @app.post("/send") async def send_message(background_tasks: BackgroundTasks, msg: str): background_tasks.add_task(write_log, msg) return {"message": "Message received"}
Background tasks run after the response is sent to the client.
FastAPI's BackgroundTasks run after the response is sent, allowing the client to get a quick response while the task runs asynchronously in the background.
Given the function def cleanup(): ..., which code snippet correctly adds it as a background task in a FastAPI endpoint?
from fastapi import FastAPI, BackgroundTasks app = FastAPI() def cleanup(): print("Cleaning up") @app.get("/clean") async def clean(background_tasks: BackgroundTasks): # Add cleanup as background task pass
Remember to pass the function itself, not call it.
The add_task method expects a function reference, not the result of calling the function.
Examine the code below. The background task is supposed to write to a file, but the file remains empty. What is the cause?
from fastapi import FastAPI, BackgroundTasks app = FastAPI() def write_log(): with open("log.txt", "a") as f: f.write("Logged\n") @app.post("/log") async def log(background_tasks: BackgroundTasks): background_tasks.add_task(write_log()) return {"status": "ok"}
Check how the function is passed to add_task.
Calling write_log() runs it immediately and passes its return (None) to add_task. The task is not scheduled. Instead, pass the function reference write_log without parentheses.
Given the code below, what will be the content of log.txt after two POST requests to /send with messages "Hello" and "World"?
from fastapi import FastAPI, BackgroundTasks app = FastAPI() def write_log(message: str): with open("log.txt", "a") as f: f.write(message + "\n") @app.post("/send") async def send(background_tasks: BackgroundTasks, msg: str): background_tasks.add_task(write_log, msg) return {"status": "sent"}
Background tasks append messages in order of requests.
Each call appends the message with a newline. After two calls with "Hello" and "World", the file has two lines in that order.
Choose the correct statement about FastAPI's BackgroundTasks compared to external task queues like Celery.
Think about persistence and reliability of tasks.
FastAPI BackgroundTasks run in the same server process and do not survive server restarts or crashes. External queues like Celery provide persistence, retries, and distributed processing.