Bird
0
0

Identify the error in this FastAPI endpoint for background file processing:

medium📝 Debug Q14 of 15
FastAPI - File Handling
Identify the error in this FastAPI endpoint for background file processing:
from fastapi import FastAPI, UploadFile, BackgroundTasks
app = FastAPI()

def process_file(file: UploadFile):
    content = file.file.read()
    with open(f"processed_{file.filename}", "wb") as f:
        f.write(content)

@app.post("/upload")
async def upload(file: UploadFile, background_tasks: BackgroundTasks):
    background_tasks.add_task(process_file, file.file.read())
    return {"message": "Processing started"}
AMissing await keyword before background_tasks.add_task call.
BPassing file.file.read() instead of file causes the file to be read too early.
Cprocess_file should be async but is defined as sync.
DFile is not saved before background task starts.
Step-by-Step Solution
Solution:
  1. Step 1: Check argument passed to add_task

    The code passes file.file.read() which reads the file immediately, not the file object.
  2. Step 2: Understand why this is a problem

    Reading the file before background task means the task gets raw bytes, not the file to read later, causing errors or empty data.
  3. Final Answer:

    Passing file.file.read() instead of file causes the file to be read too early. -> Option B
  4. Quick Check:

    Pass file object, not file.file.read() to background task [OK]
Quick Trick: Pass file object, not file.file.read(), to background task [OK]
Common Mistakes:
MISTAKES
  • Thinking add_task needs await
  • Believing process_file must be async
  • Ignoring file saving order

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes