Bird
0
0

Examine this FastAPI code snippet for background file saving:

medium📝 Debug Q6 of 15
FastAPI - File Handling
Examine this FastAPI code snippet for background file saving:
async def save_file(file: UploadFile):
    content = await file.read()
    with open(file.filename, "wb") as f:
        f.write(content)

@app.post("/upload")
async def upload(file: UploadFile, background_tasks: BackgroundTasks):
    background_tasks.add_task(save_file, file)
    return {"message": "Upload started"}

What is the main issue with this implementation?
AThe file content should be read inside the endpoint, not in save_file
BThe save_file function should not be async when used with BackgroundTasks
CThe UploadFile object cannot be used in background tasks because the file stream is closed after the request
DBackgroundTasks cannot be injected into async endpoints
Step-by-Step Solution
Solution:
  1. Step 1: Understand UploadFile lifecycle

    UploadFile's file stream is closed once the request ends.
  2. Step 2: BackgroundTasks run after response

    Background tasks run after the request finishes, so file stream is closed.
  3. Step 3: Implication

    Passing UploadFile directly to background task causes errors due to closed stream.
  4. Final Answer:

    The UploadFile object cannot be used in background tasks because the file stream is closed after the request -> Option C
  5. Quick Check:

    UploadFile streams close after request ends [OK]
Quick Trick: UploadFile streams close after request, can't use in background tasks [OK]
Common Mistakes:
MISTAKES
  • Assuming async functions can't be background tasks
  • Reading file content inside background task without preloading

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes