This project will demonstrate a Python Flask backend that runs a background task and provides real-time status updates to clients using Server-Sent Events (SSE).
Core Components:
- Flask Backend: Handles HTTP requests and serves the SSE stream.
- Background Task: A
threading.Thread simulates a long-running process.
- Shared State / Communication: An in-memory queue system (simulating a pub/sub) to broadcast messages from the background task to all connected SSE clients.
- Server-Sent Events (SSE): A browser API that allows the server to push data to the client over a single, long-lived HTTP connection.
Project Structure
sse_backend_demo/
├── app.py
└── templates/
└── index.html
1. app.py (Flask Backend)
This file will contain the Flask application, the background task logic, and the SSE endpoint.
import flask
import threading
import time
import queue
import uuid
from datetime import datetime
# Initialize Flask app
app = flask.Flask(__name__)
# --- In-memory Broadcast Mechanism ---
# This is a simplified, in-memory publish-subscribe system for SSE.
# In a real production application, you would use a dedicated message broker
# like Redis Pub/Sub, RabbitMQ, or a more robust library like Celery with WebSockets.
# A list to hold the message queues for each connected SSE client.
# Each client gets its own queue to receive broadcasts.
_sse_listeners = []
_listeners_lock = threading.Lock() # To protect access to _sse_listeners
def add_sse_listener():
"""Adds a new queue for a client to listen for SSE messages."""
q = queue.Queue()
with _listeners_lock:
_sse_listeners.append(q)
return q
def remove_sse_listener(q):
"""Removes a client's queue from the listeners list."""
with _listeners_lock:
try:
_sse_listeners.remove(q)
except ValueError:
# Already removed or never added
pass
def broadcast_sse_message(data, event="message", id=None):
"""
Broadcasts a message to all connected SSE clients.
The message is put into each client's individual queue.
"""
sse_message = f"event: {event}\n"
if id:
sse_message += f"id: {id}\n"
sse_message += f"data: {data}\n\n"
with _listeners_lock:
# Iterate over a copy to avoid issues if listeners are removed during iteration
for q in list(_sse_listeners):
try:
# Use put_nowait to avoid blocking the broadcast if a client's queue is full
q.put_nowait(sse_message)
except queue.Full:
# If a client's queue is full, they are likely too slow or disconnected.
# In a real app, you might log this or aggressively remove them.
print(f"Warning: Listener queue full, dropping message for a client. "
f"Consider removing this slow client or increasing queue size.")
remove_sse_listener(q) # Optionally remove slow consumers
# --- Background Task Logic ---
_task_counter = 0 # Simple counter for unique task IDs
def long_running_task(task_id):
"""
Simulates a long-running process that sends progress updates.
"""
broadcast_sse_message(f"Task {task_id}: Starting...", event="task_status", id=task_id)
print(f"Task {task_id}: Started.")
total_steps = 10
for i in range(1, total_steps + 1):
progress_percent = (i / total_steps) * 100
message = f"Task {task_id}: Progress {progress_percent:.0f}% (Step {i}/{total_steps})"
broadcast_sse_message(message, event="task_progress", id=task_id)
print(message)
time.sleep(1) # Simulate work
broadcast_sse_message(f"Task {task_id}: Completed!", event="task_completed", id=task_id)
print(f"Task {task_id}: Completed!")
# --- Flask Routes ---
@app.route('/')
def index():
"""Serves the main HTML page."""
return flask.render_template('index.html')
@app.route('/start-task', methods=['POST'])
def start_task():
"""
Endpoint to trigger a new background task.
"""
global _task_counter
_task_counter += 1
task_id = f"task-{_task_counter}-{uuid.uuid4().hex[:6]}" # Generate a unique task ID
thread = threading.Thread(target=long_running_task, args=(task_id,))
thread.daemon = True # Allow the main program to exit even if thread is running
thread.start()
return flask.jsonify({"status": "Task started", "task_id": task_id})
@app.route('/task-updates')
def task_updates():
"""
Server-Sent Events endpoint that streams status updates.
Each client gets their own connection and receives broadcasts.
"""
# Create a new queue for this specific client connection
client_queue = add_sse_listener()
def generate_events():
# Send an initial message to confirm connection
yield "event: connected\ndata: Connected to task updates stream.\n\n"
# Keep sending heartbeats to prevent connection timeouts
last_heartbeat = time.time()
HEARTBEAT_INTERVAL = 15 # seconds
try:
while True:
# Check for messages from the background task
# Use a timeout to allow for heartbeats
try:
message = client_queue.get(timeout=HEARTBEAT_INTERVAL)
yield message
except queue.Empty:
# Send a heartbeat if no data for a while
if time.time() - last_heartbeat > HEARTBEAT_INTERVAL:
yield f": heartbeat {datetime.now()}\n\n" # SSE comment line for heartbeat
last_heartbeat = time.time()
flask.current_app.logger.debug(f"SSE loop iteration for {flask.request.remote_addr}")
except GeneratorExit:
# Client disconnected
print(f"Client {flask.request.remote_addr} disconnected from SSE.")
except Exception as e:
# Log any other errors
print(f"Error in SSE stream for {flask.request.remote_addr}: {e}")
finally:
# Clean up the listener when the connection closes
remove_sse_listener(client_queue)
print(f"SSE listener removed for {flask.request.remote_addr}.")
# Set appropriate headers for SSE
response = flask.Response(generate_events(), mimetype='text/event-stream')
response.headers['Cache-Control'] = 'no-cache'
response.headers['X-Accel-Buffering'] = 'no' # Important for Nginx/Apache proxies
return response
# --- Run the Flask App ---
if __name__ == '__main__':
# Make sure 'templates' directory exists for render_template
import os
if not os.path.exists('templates'):
os.makedirs('templates')
app.run(debug=True, threaded=True) # threaded=True allows multiple requests concurrently
2. templates/index.html (Frontend)
This HTML file will contain the client-side JavaScript to interact with the backend, trigger tasks, and receive SSE updates.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Background Task with SSE Status Updates</title>
<style>
body { font-family: sans-serif; margin: 20px; background-color: #f4f4f4; color: #333; }
.container { max-width: 800px; margin: auto; background-color: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
h1, h2 { color: #0056b3; }
button {
padding: 10px 20px;
font-size: 16px;
background-color: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
margin-right: 10px;
transition: background-color 0.3s ease;
}
button:hover { background-color: #0056b3; }
button:disabled { background-color: #cccccc; cursor: not-allowed; }
#status-area {
margin-top: 20px;
padding: 15px;
background-color: #e9ecef;
border: 1px solid #dee2e6;
border-radius: 5px;
max-height: 400px;
overflow-y: auto;
white-space: pre-wrap; /* Preserve whitespace and line breaks */
word-break: break-word; /* Break long words */
}
.message-item {
padding: 5px 0;
border-bottom: 1px dotted #ced4da;
font-size: 0.9em;
color: #495057;
}
.message-item:last-child {
border-bottom: none;
}
.status-header {
font-weight: bold;
color: #0056b3;
}
.progress {
color: #28a745;
}
.completed {
color: #1a7e3d;
font-weight: bold;
}
</style>
</head>
<body>
<div class="container">
<h1>Background Task with SSE Status Updates</h1>
<p>This demo shows how a backend can run a long-running task and push real-time progress updates to a web client using Server-Sent Events (SSE).</p>
<button id="startTaskButton">Start New Background Task</button>
<button id="connectSseButton">Connect to Updates (SSE)</button>
<button id="disconnectSseButton" disabled>Disconnect SSE</button>
<p>Status: <span id="sseConnectionStatus" style="font-weight: bold;">Not Connected</span></p>
<h2>Task Status Updates:</h2>
<div id="status-area">
Waiting for updates...
</div>
</div>
<script>
let eventSource;
const statusArea = document.getElementById('status-area');
const startTaskButton = document.getElementById('startTaskButton');
const connectSseButton = document.getElementById('connectSseButton');
const disconnectSseButton = document.getElementById('disconnectSseButton');
const sseConnectionStatus = document.getElementById('sseConnectionStatus');
function appendMessage(message, className = '') {
const now = new Date().toLocaleTimeString();
const messageElement = document.createElement('div');
messageElement.classList.add('message-item');
if (className) {
messageElement.classList.add(className);
}
messageElement.innerHTML = `<span style="color: #6c757d;">[${now}]</span> ${message}`;
statusArea.appendChild(messageElement);
statusArea.scrollTop = statusArea.scrollHeight; // Auto-scroll to bottom
}
function connectToSse() {
if (eventSource) {
appendMessage("Already connected to SSE.", "status-header");
return;
}
eventSource = new EventSource('/task-updates');
appendMessage("Attempting to connect to SSE stream...", "status-header");
sseConnectionStatus.textContent = "Connecting...";
eventSource.onopen = function() {
appendMessage("SSE connection established.", "status-header");
sseConnectionStatus.textContent = "Connected";
connectSseButton.disabled = true;
disconnectSseButton.disabled = false;
};
eventSource.onmessage = function(event) {
// This 'message' event catches anything not explicitly named by 'event:' field
console.log("Generic SSE message:", event.data);
appendMessage(`[GENERIC]: ${event.data}`);
};
eventSource.addEventListener('connected', function(event) {
appendMessage(`[SERVER]: ${event.data}`, "status-header");
});
eventSource.addEventListener('task_status', function(event) {
appendMessage(`[STATUS]: ${event.data}`, "status-header");
});
eventSource.addEventListener('task_progress', function(event) {
appendMessage(`[PROGRESS]: ${event.data}`, "progress");
});
eventSource.addEventListener('task_completed', function(event) {
appendMessage(`[COMPLETED]: ${event.data}`, "completed");
});
eventSource.onerror = function(error) {
console.error("SSE Error:", error);
eventSource.close();
eventSource = null;
appendMessage("SSE connection error or closed. Reconnecting might be needed.", "error");
sseConnectionStatus.textContent = "Disconnected (Error)";
connectSseButton.disabled = false;
disconnectSseButton.disabled = true;
};
}
function disconnectSse() {
if (eventSource) {
eventSource.close();
eventSource = null;
appendMessage("SSE connection explicitly closed.", "status-header");
sseConnectionStatus.textContent = "Disconnected";
connectSseButton.disabled = false;
disconnectSseButton.disabled = true;
} else {
appendMessage("No active SSE connection to disconnect.", "status-header");
}
}
startTaskButton.addEventListener('click', async () => {
appendMessage("Sending request to start new task...", "status-header");
try {
const response = await fetch('/start-task', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
const data = await response.json();
if (response.ok) {
appendMessage(`Task started successfully! Task ID: ${data.task_id}`, "status-header");
} else {
appendMessage(`Error starting task: ${data.status || response.statusText}`, "error");
}
} catch (error) {
appendMessage(`Network error starting task: ${error}`, "error");
}
});
connectSseButton.addEventListener('click', connectToSse);
disconnectSseButton.addEventListener('click', disconnectSse);
// Initial connection on page load (optional, you can make it button-triggered only)
// connectToSse();
</script>
</body>
</html>
How to Run
-
Save the files:
- Create a folder named
sse_backend_demo.
- Inside
sse_backend_demo, create app.py.
- Inside
sse_backend_demo, create a folder named templates.
- Inside
templates, create index.html.
-
Install Flask:
If you don't have Flask installed, open your terminal or command prompt and run:
pip install Flask
-
Run the Flask application:
Navigate to the sse_backend_demo directory in your terminal and run:
python app.py
-
Open in browser:
Open your web browser and go to http://127.0.0.1:5000/.
Explanation
Backend (app.py)
_sse_listeners and _listeners_lock: These form a basic in-memory pub/sub system. When a client connects to the SSE endpoint, a new queue.Queue is added to _sse_listeners.
broadcast_sse_message: This function is called by the background task. It takes a message and puts it into every queue.Queue in _sse_listeners. This ensures all connected clients receive the update.
long_running_task(task_id): This function simulates work using time.sleep() and calls broadcast_sse_message at different stages to send progress updates. Each message includes an event type (task_status, task_progress, task_completed) and an id for better client-side handling.
/start-task: This endpoint is a POST request that, when called, spins up a new threading.Thread to run long_running_task. It assigns a unique task_id for tracking.
/task-updates: This is the heart of the SSE.
- It creates a
Response object with mimetype='text/event-stream'.
- The
generate_events() function is a Python generator. When a client connects, this generator starts running.
- It calls
add_sse_listener() to get a new dedicated queue for this client.
- Inside the
while True loop, it attempts to get() messages from its client_queue. queue.get(timeout=HEARTBEAT_INTERVAL) is used so the loop doesn't block indefinitely if there are no messages, allowing it to send heartbeat comments to keep the connection alive.
- Messages retrieved from the queue are yielded in the SSE format (
event: type\nid: id\ndata: payload\n\n).
- The
try...finally block ensures remove_sse_listener() is called when the client disconnects or an error occurs, cleaning up the unused queue.
Frontend (index.html)
- HTML Structure: Simple buttons and a
div to display updates.
EventSource API: This is the browser's built-in API for SSE.
new EventSource('/task-updates'): Establishes the connection to the SSE endpoint.
eventSource.onopen: Fired when the connection is successfully established.
eventSource.onmessage: Catches any SSE message without an event: field.
eventSource.addEventListener('eventName', function(event) { ... }): This is crucial. It allows listening for specific event types pushed from the server (e.g., task_status, task_progress, task_completed, connected). The event.data property contains the message payload.
eventSource.onerror: Fired if the connection encounters an error or closes.
fetch('/start-task'): An asynchronous JavaScript function to send a POST request to the backend to initiate a new task.
- UI Updates: Messages received via SSE are appended to the
status-area div, providing real-time feedback.
Considerations for Production
- Concurrency & Scaling:
threading.Thread is suitable for simple demos but has limitations for high concurrency and robustness. For production, consider:
- Asynchronous Frameworks: FastAPI or Starlette with
asyncio for highly concurrent I/O.
- Background Task Queues: Celery (with Redis or RabbitMQ) or RQ (with Redis) are robust solutions for running tasks outside the main web process, providing persistence, retries, and monitoring.
- SSE/WebSockets: For robust real-time communication across many clients, a dedicated message broker (like Redis Pub/Sub) combined with WebSockets (e.g., with
Flask-SocketIO or FastAPI's WebSockets) is often preferred over raw SSE, especially if two-way communication is needed. SSE is uni-directional (server to client).
- State Management: The in-memory
_sse_listeners list is not suitable for multi-process deployments (e.g., running Flask with Gunicorn/uWSGI) because each process would have its own isolated list. A shared external message broker (like Redis) is essential for broadcasting messages across multiple backend processes.
- Error Handling & Retries: Implement more robust error handling for background tasks and client connections (e.g., automatic SSE reconnect logic).
- Authentication/Authorization: Secure your API endpoints.
- Client Management: For a very large number of SSE connections, managing them efficiently becomes important.