Here's a Python backend using FastAPI with a background task and Server-Sent Events (SSE) to provide real-time progress updates:
from fastapi import FastAPI, BackgroundTasks, Request
from fastapi.responses import StreamingResponse
from fastapi.middleware.cors import CORSMiddleware
import asyncio
import time
import uuid
import json
app = FastAPI()
# Enable CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Store for task progress
tasks = {}
async def long_running_task(task_id: str):
"""Simulate a long-running task with progress updates"""
total_steps = 10
for step in range(1, total_steps + 1):
# Update task progress
progress = (step / total_steps) * 100
tasks[task_id] = {
"id": task_id,
"progress": progress,
"status": "running" if progress < 100 else "completed",
"message": f"Processing step {step}/{total_steps}"
}
# Simulate work
await asyncio.sleep(1)
# Task completed
tasks[task_id]["status"] = "completed"
tasks[task_id]["message"] = "Task completed successfully"
# Keep completed task info for a while
await asyncio.sleep(60)
if task_id in tasks:
del tasks[task_id]
@app.post("/start-task")
async def start_task(background_tasks: BackgroundTasks):
"""Start a new background task and return its ID"""
task_id = str(uuid.uuid4())
# Initialize task status
tasks[task_id] = {
"id": task_id,
"progress": 0,
"status": "starting",
"message": "Task is being initialized"
}
# Start the task in the background
background_tasks.add_task(long_running_task, task_id)
return {"task_id": task_id}
@app.get("/task/{task_id}")
async def get_task_status(task_id: str):
"""Get the current status of a task"""
if task_id not in tasks:
return {"error": "Task not found"}
return tasks[task_id]
async def task_status_event_generator(request: Request, task_id: str):
"""Generate SSE events with task status updates"""
if task_id not in tasks:
yield f"data: {json.dumps({'error': 'Task not found'})}\n\n"
return
while True:
# Check if client disconnected
if await request.is_disconnected():
break
# Get current task status
status = tasks.get(task_id)
if not status:
yield f"data: {json.dumps({'error': 'Task not found'})}\n\n"
break
# Send the status update
yield f"data: {json.dumps(status)}\n\n"
# If task is completed, send one more update and stop
if status["status"] == "completed":
await asyncio.sleep(1)
break
await asyncio.sleep(0.5)
@app.get("/task/{task_id}/events")
async def task_status_events(request: Request, task_id: str):
"""SSE endpoint for real-time task status updates"""
return StreamingResponse(
task_status_event_generator(request, task_id),
media_type="text/event-stream"
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
Would you like me to explain or break down this code?