0
0
FastAPIframework~20 mins

Background file processing in FastAPI - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Background Processing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens when a background task is added in FastAPI?
Consider this FastAPI code snippet that uploads a file and starts a background task to process it. What is the behavior of the endpoint when a file is uploaded?
FastAPI
from fastapi import FastAPI, UploadFile, BackgroundTasks

app = FastAPI()

def process_file(file_path: str):
    # Simulate file processing
    with open(file_path, 'r') as f:
        data = f.read()
    print(f"Processed file with length: {len(data)}")

@app.post('/upload')
async def upload_file(background_tasks: BackgroundTasks, file: UploadFile):
    file_location = f"./temp/{file.filename}"
    with open(file_location, 'wb') as buffer:
        buffer.write(await file.read())
    background_tasks.add_task(process_file, file_location)
    return {"message": "File received, processing started"}
AThe endpoint returns an error because background tasks cannot be used with file uploads.
BThe endpoint waits until the file processing finishes before returning the response.
CThe endpoint immediately returns the response while the file processing runs in the background.
DThe file processing runs synchronously before the file is saved.
Attempts:
2 left
💡 Hint
Think about how FastAPI handles background tasks and response timing.
📝 Syntax
intermediate
2:00remaining
Identify the syntax error in this FastAPI background task usage
Which option contains a syntax error that prevents the background task from being added correctly?
FastAPI
from fastapi import FastAPI, BackgroundTasks

app = FastAPI()

def task(name: str):
    print(f"Hello {name}")

@app.get('/start')
async def start(background_tasks: BackgroundTasks):
    background_tasks.add_task(task, 'User')
    return {"status": "started"}
Abackground_tasks.add_task(task, ['User'])
Bbackground_tasks.add_task(task, 'User')
Cbackground_tasks.add_task(task, name='User')
Dbackground_tasks.add_task(task 'User')
Attempts:
2 left
💡 Hint
Check the syntax of function calls and argument passing.
state_output
advanced
2:00remaining
What is printed when multiple background tasks modify a shared list?
Given this FastAPI code, what will be the final content of the shared list after the endpoint is called once?
FastAPI
from fastapi import FastAPI, BackgroundTasks
import time

app = FastAPI()
shared_list = []

def add_item(item: str):
    time.sleep(0.1)
    shared_list.append(item)

@app.get('/add')
async def add(background_tasks: BackgroundTasks):
    background_tasks.add_task(add_item, 'A')
    background_tasks.add_task(add_item, 'B')
    return {"message": "Tasks started"}
A['B', 'A']
B['A', 'B']
C[]
D['A']
Attempts:
2 left
💡 Hint
Background tasks run after response, but order of execution is preserved.
🔧 Debug
advanced
2:00remaining
Why does this background task fail to process the uploaded file?
This FastAPI code tries to process an uploaded file in the background but fails. What is the cause?
FastAPI
from fastapi import FastAPI, UploadFile, BackgroundTasks

app = FastAPI()

def process_file(file: UploadFile):
    content = file.file.read()
    print(f"File content length: {len(content)}")

@app.post('/upload')
async def upload(background_tasks: BackgroundTasks, file: UploadFile):
    background_tasks.add_task(process_file, file)
    return {"message": "Processing started"}
AThe UploadFile object is closed before the background task runs, so reading fails.
BBackgroundTasks cannot accept functions with parameters.
CThe process_file function must be async to work as a background task.
DThe file content must be saved to disk before processing.
Attempts:
2 left
💡 Hint
Think about the lifecycle of UploadFile and when its file handle is available.
🧠 Conceptual
expert
2:00remaining
Which statement about FastAPI background tasks and concurrency is true?
Select the correct statement about how FastAPI handles background tasks and concurrency.
ABackground tasks run after the response is sent but share the same event loop, so CPU-bound tasks can block the server.
BBackground tasks run in separate threads and can safely modify shared memory without locks.
CBackground tasks run in separate processes automatically to avoid blocking the main server.
DBackground tasks are executed synchronously before the response is returned.
Attempts:
2 left
💡 Hint
Consider how FastAPI uses async and the Python event loop for background tasks.