Real-Time Features with Flask-SocketIO
Introduction
Real-time features, such as WebSockets, allow applications to send and receive data instantly without refreshing the page. Flask-SocketIO makes it easy to integrate WebSocket communication into a Flask application, enabling live notifications and updates.
This article explains how to build real-time features using Flask-SocketIO, with practical examples for notifications and live updates.
Step 1: Install Flask-SocketIO and Dependencies
Install Flask-SocketIO and its WebSocket dependency:
pip install flask-socketio eventlet
Step 2: Set Up Flask-SocketIO
Update your Flask application to include Flask-SocketIO:
from flask import Flask, render_template from flask_socketio import SocketIO app = Flask(__name__) socketio = SocketIO(app) @app.route('/') def index(): return '''Real-Time Updates
''' @socketio.on('new_message') def handle_message(data): print(f"Received message: {data}") socketio.emit('update', f"Server received: {data}")
Step 3: Start the Application
Run the Flask application with Flask-SocketIO:
socketio.run(app, debug=True)
Access the app in your browser. Clicking "Send Message" sends a WebSocket message to the server, which broadcasts an update to all clients.
Step 4: Adding Notifications
Add a notification example to your application:
@socketio.on('notify') def handle_notification(data): print(f"Notification: {data}") socketio.emit('notification', f"New notification: {data}")
Update the JavaScript in the template to handle notifications:
socket.on('notification', function(data) { alert(data); }); function sendNotification() { socket.emit('notify', 'You have a new notification!'); }
Add a button in the HTML:
<button onclick="sendNotification()">Send Notification</button>
Step 5: Broadcasting Live Updates
Implement live updates, such as a live chat or dashboard updates:
@app.route('/broadcast') def broadcast(): socketio.emit('update', 'This is a broadcast update!') return "Broadcast sent!"
Access /broadcast
in your browser to send a broadcast message to all connected clients.
Conclusion
By integrating Flask-SocketIO, you can easily add real-time features to your Flask application, such as WebSocket-based communication, live notifications, and updates. This improves user interaction and application responsiveness.