Flask-SocketIO lets your Flask app talk to web browsers in real time. It helps send and receive messages instantly without refreshing the page.
Flask-SocketIO setup
from flask import Flask from flask_socketio import SocketIO app = Flask(__name__) socketio = SocketIO(app) if __name__ == '__main__': socketio.run(app)
Import SocketIO from flask_socketio to add real-time features.
Create a SocketIO object by passing your Flask app to it.
from flask import Flask from flask_socketio import SocketIO app = Flask(__name__) socketio = SocketIO(app) if __name__ == '__main__': socketio.run(app, debug=True)
from flask import Flask from flask_socketio import SocketIO app = Flask(__name__) socketio = SocketIO(app, cors_allowed_origins='*') if __name__ == '__main__': socketio.run(app)
This simple Flask app uses Flask-SocketIO to connect with the browser. When the page loads, the browser sends a message to the server. The server prints it and replies back. The browser then shows the server's reply on the page.
from flask import Flask, render_template_string from flask_socketio import SocketIO, emit app = Flask(__name__) socketio = SocketIO(app) html = ''' <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Flask-SocketIO Test</title> <script src="https://cdn.socket.io/4.5.4/socket.io.min.js"></script> <script> document.addEventListener('DOMContentLoaded', () => { const socket = io(); socket.on('connect', () => { console.log('Connected to server'); socket.emit('my_event', {data: 'Hello Server!'}); }); socket.on('my_response', msg => { const p = document.createElement('p'); p.textContent = 'Server says: ' + msg.data; document.body.appendChild(p); }); }); </script> </head> <body> <h1>Flask-SocketIO Setup Test</h1> </body> </html> ''' @app.route('/') def index(): return render_template_string(html) @socketio.on('my_event') def handle_my_event(json): print('Received:', json) emit('my_response', {'data': 'Got your message!'}) if __name__ == '__main__': socketio.run(app, debug=True)
Make sure to install flask-socketio with pip install flask-socketio.
Use the socketio.run(app) method instead of app.run() to enable WebSocket support.
Include the Socket.IO client script in your HTML to connect from the browser.
Flask-SocketIO adds real-time communication to Flask apps.
Set it up by creating a SocketIO object with your Flask app.
Use socketio.run(app) to run your app with WebSocket support.