Background file processing lets your app handle big or slow tasks without making users wait. It runs tasks behind the scenes while your app stays fast and responsive.
Background file processing in FastAPI
from fastapi import FastAPI, BackgroundTasks, UploadFile app = FastAPI() def process_file(file_path: str): # Your file processing logic here pass @app.post("/upload") async def upload_file(background_tasks: BackgroundTasks, file: UploadFile): file_location = f"files/{file.filename}" with open(file_location, "wb") as f: f.write(await file.read()) background_tasks.add_task(process_file, file_location) return {"message": "File uploaded and processing started"}
Use BackgroundTasks to add tasks that run after the response is sent.
File processing functions should be normal functions, not async, to avoid blocking.
def process_file(file_path: str): print(f"Processing {file_path}")
process_file function to run in the background with the file path argument.background_tasks.add_task(process_file, "files/myfile.txt")@app.post("/upload") async def upload(background_tasks: BackgroundTasks, file: UploadFile): file_location = f"files/{file.filename}" with open(file_location, "wb") as f: f.write(await file.read()) background_tasks.add_task(process_file, file_location) return {"message": "Upload successful"}
This FastAPI app uploads a file, saves it, and then processes it in the background. The user gets an immediate response while the file is processed behind the scenes.
from fastapi import FastAPI, BackgroundTasks, UploadFile import time app = FastAPI() def process_file(file_path: str): # Simulate a slow file processing task print(f"Start processing {file_path}") time.sleep(3) # pretend to do work print(f"Finished processing {file_path}") @app.post("/upload") async def upload(background_tasks: BackgroundTasks, file: UploadFile): file_location = f"files/{file.filename}" with open(file_location, "wb") as f: f.write(await file.read()) background_tasks.add_task(process_file, file_location) return {"message": "File uploaded and processing started"}
Background tasks run after the response is sent, so users don't wait.
Make sure the file saving happens before starting background processing.
Background tasks are good for small to medium jobs; for heavy jobs consider task queues like Celery.
Background file processing keeps your app fast by running slow tasks after response.
Use FastAPI's BackgroundTasks to add these tasks easily.
Always save files first, then start background processing.