How to Create Real Time App with Flask Using Flask-SocketIO
To create a real-time app with
Flask, use the Flask-SocketIO extension which enables WebSocket communication. This allows your server and clients to send and receive messages instantly without page reloads.Syntax
The basic syntax involves importing Flask and SocketIO, initializing them, and defining event handlers for real-time communication.
SocketIO(app): Wraps your Flask app to enable WebSocket support.@socketio.on('event_name'): Decorator to listen for events from clients.socketio.emit('event_name', data): Sends data to clients.socketio.run(app): Runs the app with WebSocket support.
python
from flask import Flask from flask_socketio import SocketIO, emit app = Flask(__name__) socketio = SocketIO(app) @socketio.on('message') def handle_message(msg): emit('response', {'data': msg}, broadcast=True) if __name__ == '__main__': socketio.run(app)
Example
This example shows a simple chat app where clients send messages to the server, and the server broadcasts them to all connected clients instantly.
python
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('send_message') def handle_send_message(data): emit('receive_message', data, broadcast=True) if __name__ == '__main__': socketio.run(app, debug=True)
Output
Running on http://127.0.0.1:5000/ with WebSocket support
Common Pitfalls
- Not installing
flask-socketioor missing dependencies likeeventletorgeventcan cause errors. - Running the app with
app.run()instead ofsocketio.run(app)disables WebSocket support. - Forgetting to include client-side Socket.IO JavaScript library will prevent real-time communication.
- Not handling CORS properly can block connections in browsers.
python
## Wrong way (no SocketIO run): # app.run() ## Right way: socketio.run(app)
Quick Reference
| Feature | Usage |
|---|---|
| Initialize SocketIO | socketio = SocketIO(app) |
| Listen to event | @socketio.on('event_name') |
| Emit event | socketio.emit('event_name', data) |
| Run app with WebSocket | socketio.run(app) |
| Broadcast message | emit('event', data, broadcast=True) |
Key Takeaways
Use Flask-SocketIO to add real-time WebSocket support to your Flask app.
Always run your app with socketio.run(app) to enable real-time features.
Define event handlers with @socketio.on to respond to client messages.
Broadcast messages to all clients using emit with broadcast=True.
Ensure client-side includes Socket.IO JavaScript for communication.