Performance: Background file processing
This concept affects page load speed and interaction responsiveness by offloading heavy file processing tasks from the main request thread.
Jump into concepts and practice - no test required
from fastapi import FastAPI, UploadFile, BackgroundTasks app = FastAPI() def heavy_processing(content: bytes): # Process file in background pass @app.post('/upload') async def upload(file: UploadFile, background_tasks: BackgroundTasks): content = await file.read() background_tasks.add_task(heavy_processing, content) return {'status': 'processing started'}
from fastapi import FastAPI, UploadFile app = FastAPI() @app.post('/upload') async def upload(file: UploadFile): content = await file.read() # Process file synchronously here result = heavy_processing(content) return {'status': 'done', 'result': result}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous file processing in request | N/A | N/A | Blocks response, delays paint | [X] Bad |
| Background file processing with BackgroundTasks | N/A | N/A | Immediate response, no blocking | [OK] Good |
BackgroundTasks in FastAPI for file processing?from fastapi import FastAPI, UploadFile, BackgroundTasks
app = FastAPI()
def save_file(file: UploadFile):
with open(f"saved_{file.filename}", "wb") as f:
f.write(file.file.read())
@app.post("/upload")
async def upload(file: UploadFile, background_tasks: BackgroundTasks):
background_tasks.add_task(save_file, file)
return {"message": "File upload started"}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"}