Step-by-step guide to Flask-SocketIO for real-time ML updates; seamlessly integrate live ML insights into your app.

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
// Import necessary Python modules
from flask import Flask, render_template // Flask to create web app and render_template for HTML pages
from flask\_socketio import SocketIO, emit // SocketIO for WebSocket communication
// Initialize Flask app
app = Flask(**name**)
app.config['SECRET_KEY'] = "your_secret\_key" // Secret key for session management
// Initialize SocketIO with the Flask app
socketio = SocketIO(app)
// Example: Using a dummy function to simulate an ML prediction
def load\_model():
// In a real scenario, load your pre-trained ML model here
return "dummy\_model"
model = load\_model() // Load the model
def process_and_predict(data):
// Process the incoming data if necessary. For now, we'll assume data is ready.
// Use the model to predict.
prediction = "predicted\_value" // Replace with model.predict(data) when using a proper ML model
return prediction
// Handle client connection
@socketio.on('connect')
def handle\_connect():
// Log connection and send an initial welcome message to the client
print("Client connected")
emit('server\_response', {'data': 'Welcome! Ready to receive ML updates.'})
// Listen for a custom event 'ml\_update' carrying new data for prediction
@socketio.on('ml\_update')
def handle_ml_update(json\_data):
// Log received data from client
print("Received data for ML update: ", json\_data)
// Extract pertinent information for ML processing
input_data = json_data.get('input') // Expect client to send data under key 'input'
// Get ML prediction
prediction = process_and_predict(input\_data)
// Emit the ML result back to the requesting client using event 'prediction\_result'
emit('prediction\_result', {'prediction': prediction})
// For example, sending periodic updates from a long-running ML process
def background_ml_task():
import time
for progress in range(0, 101, 10):
// Simulate time-consuming ML work
time.sleep(1)
// Broadcast the progress update to all connected clients (broadcast=True)
socketio.emit('progress\_update', {'progress': progress}, broadcast=True)
// You might run the background_ml_task in a separate thread to avoid blocking the main server loop
/_ Client-side JavaScript snippet _/
// Connect to the Flask-SocketIO server
var socket = io.connect('http://' + document.domain + ':' + location.port);
// Listen for a welcome message
socket.on('server\_response', function(msg) {
console.log(msg.data);
});
// Listen for prediction results from the server
socket.on('prediction\_result', function(data) {
console.log("Prediction received:", data.prediction);
});
// Listen for broadcasted progress updates
socket.on('progress\_update', function(data) {
console.log("ML Task Progress:", data.progress);
});
// Emit event to request ML prediction when needed
function sendMLData(inputValue) {
socket.emit('ml\_update', {input: inputValue});
}
// Run the Flask-SocketIO server
if **name** == '**main**':
socketio.run(app, debug=True) // debug=True for development; remove in production
From startups to enterprises and everything in between, see for yourself our incredible impact.
Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We’ll discuss your project and provide a custom quote at no cost.Â