Real-time means your app updates instantly without waiting. It helps users see fresh info right away, making apps feel fast and alive.
Why real-time matters in Flask
from flask import Flask, render_template from flask_socketio import SocketIO, emit app = Flask(__name__) socketio = SocketIO(app) @app.route('/') def index(): return render_template('index.html') @socketio.on('message') def handle_message(msg): emit('message', msg, broadcast=True) if __name__ == '__main__': socketio.run(app)
Flask alone handles normal web requests, but for real-time updates, Flask-SocketIO adds instant communication.
SocketIO uses WebSockets under the hood to keep a live connection open between client and server.
socketio.emit('update', {'data': 'new info'})
@socketio.on('join') def on_join(data): room = data['room'] join_room(room) emit('status', {'msg': 'User joined room'}, room=room)
This simple Flask app uses Flask-SocketIO to send and receive messages instantly. The client sends a message after 1 second, and the server broadcasts a response that appears on the page immediately.
from flask import Flask from flask_socketio import SocketIO, emit app = Flask(__name__) socketio = SocketIO(app) @app.route('/') def index(): return ''' <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Real-time Demo</title> <script src="https://cdn.socket.io/4.5.4/socket.io.min.js"></script> <script> document.addEventListener('DOMContentLoaded', () => { const socket = io(); socket.on('message', msg => { const p = document.createElement('p'); p.textContent = msg; document.body.appendChild(p); }); setTimeout(() => { socket.emit('message', 'Hello from client!'); }, 1000); }); </script> </head> <body> <h1>Real-time message will appear below:</h1> </body> </html> ''' @socketio.on('message') def handle_message(msg): emit('message', f'Server received: {msg}', broadcast=True) if __name__ == '__main__': socketio.run(app)
Real-time apps need a way to keep connections open; Flask-SocketIO helps with that.
Test real-time features in a browser and watch messages appear without refreshing.
Real-time can improve user experience but may add complexity to your app.
Real-time means instant updates without page reloads.
Flask alone is not real-time; Flask-SocketIO adds this ability.
Use real-time for chat, live updates, and notifications.