Bird
0
0

You want to save an uploaded file immediately and then process it in the background. Which FastAPI code snippet correctly implements this pattern?

hard🚀 Application Q15 of 15
FastAPI - File Handling
You want to save an uploaded file immediately and then process it in the background. Which FastAPI code snippet correctly implements this pattern?
Aasync def upload(file: UploadFile, background_tasks: BackgroundTasks): background_tasks.add_task(process_file, file) return {"message": "Processing started"}
Basync def upload(file: UploadFile): contents = await file.read() with open(f"saved_{file.filename}", "wb") as f: f.write(contents) process_file(f"saved_{file.filename}") return {"message": "File saved and processed"}
Casync def upload(file: UploadFile, background_tasks: BackgroundTasks): contents = await file.read() with open(f"saved_{file.filename}", "wb") as f: f.write(contents) background_tasks.add_task(process_file, f"saved_{file.filename}") return {"message": "File saved and processing started"}
Dasync def upload(file: UploadFile, background_tasks: BackgroundTasks): background_tasks.add_task(process_file, file.file.read()) return {"message": "Processing started"}
Step-by-Step Solution
Solution:
  1. Step 1: Save file before background processing

    The file is read and saved immediately using await file.read() and writing to disk.
  2. Step 2: Add background task with saved filename

    The background task processes the saved file path, ensuring file exists before processing.
  3. Final Answer:

    Save file first, then add background task with saved filename. -> Option C
  4. Quick Check:

    Save file first, then background task with filename [OK]
Quick Trick: Save file first, then add background task with filename [OK]
Common Mistakes:
MISTAKES
  • Adding background task before saving file
  • Passing file.file.read() instead of file or filename
  • Calling process_file synchronously inside endpoint

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes