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.
Practice
Solution
Step 1: Understand Flask-SocketIO's role
Flask-SocketIO is designed to enable real-time communication between clients and the server using WebSockets.Step 2: Compare options with Flask-SocketIO's purpose
Database migrations, static files, and REST APIs are handled by other Flask extensions or core Flask features, not Flask-SocketIO.Final Answer:
To add real-time communication using WebSockets -> Option AQuick Check:
Flask-SocketIO = real-time communication [OK]
- Confusing Flask-SocketIO with database or static file handling
- Thinking it creates REST APIs
- Assuming it runs the Flask app without WebSocket support
app?Solution
Step 1: Recall Flask-SocketIO initialization syntax
You create a SocketIO object by passing the Flask app instance to it: SocketIO(app).Step 2: Analyze each option
socketio = SocketIO(app) correctly passesapptoSocketIO. socketio = SocketIO() misses the app argument. socketio = SocketIO.run(app) wrongly callsrunduring initialization. socketio = SocketIO(app.run) incorrectly passesapp.runinstead ofapp.Final Answer:
socketio = SocketIO(app) -> Option BQuick Check:
SocketIO initialized with app = socketio = SocketIO(app) [OK]
- Forgetting to pass the app instance
- Calling run() during initialization
- Passing app.run instead of app
from flask import Flask
from flask_socketio import SocketIO
app = Flask(__name__)
socketio = SocketIO(app)
if __name__ == '__main__':
socketio.run(app)Solution
Step 1: Understand socketio.run(app) behavior
Callingsocketio.run(app)runs the Flask app with WebSocket support enabled by Flask-SocketIO.Step 2: Check for errors or missing parameters
The code imports correctly, initializes SocketIO with the app, and callssocketio.run(app)inside the main guard, which is the correct pattern.Final Answer:
The Flask app runs with WebSocket support enabled -> Option DQuick Check:
socketio.run(app) enables WebSocket support [OK]
- Thinking socketio.run is invalid
- Assuming WebSocket support is automatic without socketio.run
- Confusing socketio.run with app.run
from flask import Flask
from flask_socketio import SocketIO
app = Flask(__name__)
socketio = SocketIO()
if __name__ == '__main__':
socketio.run(app)Solution
Step 1: Check SocketIO initialization
SocketIO must be initialized with the Flask app instance by passingapptoSocketIO(). Here, it is called without arguments.Step 2: Verify other parts of the code
socketio.run(app) is correct to run the app with WebSocket support. Flask app is correctly created with__name__. Flask-SocketIO is imported properly.Final Answer:
SocketIO is not initialized with the Flask app instance -> Option CQuick Check:
SocketIO needs app argument during initialization [OK]
- Forgetting to pass app to SocketIO()
- Confusing socketio.run with app.run
- Assuming Flask app needs extra arguments
Solution
Step 1: Confirm SocketIO initialization with app
from flask import Flask from flask_socketio import SocketIO app = Flask(__name__) socketio = SocketIO(app) if __name__ == '__main__': socketio.run(app, host='0.0.0.0', port=5000) correctly initializes SocketIO with the Flask app instance.Step 2: Check how the app is run
from flask import Flask from flask_socketio import SocketIO app = Flask(__name__) socketio = SocketIO(app) if __name__ == '__main__': socketio.run(app, host='0.0.0.0', port=5000) usessocketio.run(app, host='0.0.0.0', port=5000)which runs the app with WebSocket support and listens on all interfaces at port 5000. Other options either miss passing app to SocketIO, use app.run() which lacks WebSocket support, or call socketio.run() without app.Final Answer:
from flask import Flask from flask_socketio import SocketIO app = Flask(__name__) socketio = SocketIO(app) if __name__ == '__main__': socketio.run(app, host='0.0.0.0', port=5000) -> Option AQuick Check:
socketio = SocketIO(app); socketio.run(app, host='0.0.0.0', port=5000) [OK]
- Calling app.run() instead of socketio.run() to start app
- Not passing app to SocketIO()
- Calling socketio.run() without app argument
Ready to prove it?
Pass the test and this pattern moves unknown
