Server-Sent Events (SSE) let a server send updates to a web page automatically. Sometimes, you need another way to do this, like using WebSockets, which allow two-way communication between the server and the browser.
Server-Sent Events alternative 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('response', msg, broadcast=True) if __name__ == '__main__': socketio.run(app)
This example uses Flask-SocketIO, a popular Flask extension for WebSockets.
WebSockets allow two-way communication, unlike SSE which is one-way from server to client.
from flask_socketio import SocketIO socketio = SocketIO(app) @socketio.on('connect') def on_connect(): print('Client connected')
@socketio.on('chat message') def handle_chat(msg): emit('chat response', msg, broadcast=True)
This is a simple chat app using Flask and WebSockets. When you type a message and click send, it goes to the server and then broadcasts to all connected clients, updating their message list instantly.
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"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>WebSocket Chat</title> <script src="https://cdn.socket.io/4.5.4/socket.io.min.js"></script> </head> <body> <h1>Simple WebSocket Chat</h1> <input id="msgInput" autocomplete="off" placeholder="Type message..." /> <button onclick="sendMessage()">Send</button> <ul id="messages"></ul> <script> const socket = io(); const messages = document.getElementById('messages'); socket.on('chat response', function(msg) { const li = document.createElement('li'); li.textContent = msg; messages.appendChild(li); }); function sendMessage() { const input = document.getElementById('msgInput'); if(input.value.trim() !== '') { socket.emit('chat message', input.value); input.value = ''; } } </script> </body> </html> ''' @app.route('/') def index(): return render_template_string(html) @socketio.on('chat message') def handle_chat_message(msg): emit('chat response', msg, broadcast=True) if __name__ == '__main__': socketio.run(app, debug=True)
WebSockets require a client library like Socket.IO to work smoothly with Flask.
Unlike SSE, WebSockets allow the client to send messages to the server too.
Make sure to run the Flask app with SocketIO's run method, not the usual app.run().
Server-Sent Events send updates one-way from server to browser.
WebSockets are a good alternative for two-way real-time communication.
Flask-SocketIO makes it easy to add WebSockets to your Flask app.
Practice
Solution
Step 1: Understand SSE purpose
Server-Sent Events send updates one-way from server to browser for real-time data.Step 2: Identify alternative for two-way communication
WebSockets allow two-way real-time communication and Flask-SocketIO simplifies their use in Flask.Final Answer:
WebSockets using Flask-SocketIO -> Option CQuick Check:
Real-time two-way communication = WebSockets [OK]
- Confusing SSE with regular HTTP requests
- Thinking static pages can update in real-time
- Assuming email is real-time communication
Solution
Step 1: Recall correct import syntax in Python
Python uses 'from module import class' to import specific classes.Step 2: Match Flask-SocketIO import pattern
The correct import is 'from flask_socketio import SocketIO' to get the SocketIO class.Final Answer:
from flask_socketio import SocketIO -> Option AQuick Check:
Correct Python import syntax = from flask_socketio import SocketIO [OK]
- Using JavaScript import syntax in Python
- Importing SocketIO from flask instead of flask_socketio
- Incorrect module or class names
from flask_socketio import SocketIO, emit
socketio = SocketIO(app)
@socketio.on('connect')
def handle_connect():
emit('message', {'data': 'Welcome!'})Solution
Step 1: Understand the emit function usage
emit sends an event with a dictionary payload as JSON to the client.Step 2: Analyze the event and data sent on connect
On 'connect', the server emits 'message' event with {'data': 'Welcome!'} dictionary.Final Answer:
A JSON object with {'data': 'Welcome!'} -> Option DQuick Check:
emit sends JSON data = A JSON object with {'data': 'Welcome!'} [OK]
- Thinking emit sends plain text only
- Assuming emit requires string, not dict
- Believing no message is sent on connect
from flask_socketio import SocketIO
socketio = SocketIO(app)
@socketio.on('message')
def handle_message(data):
print('Received:', data)
socketio.run(app)Solution
Step 1: Check imports and app definition
The code uses 'app' but does not import or define it anywhere.Step 2: Confirm socketio.run usage
socketio.run(app) is correct to run the app with SocketIO support.Final Answer:
Missing import of Flask app -> Option BQuick Check:
Undefined app variable = Missing import of Flask app [OK]
- Confusing socketio.run with app.run
- Thinking event handlers must return values
- Assuming 'connect' event handler is mandatory
Solution
Step 1: Understand broadcasting in Flask-SocketIO
To send a message to all clients, use socketio.emit with broadcast=True.Step 2: Evaluate options for broadcasting
Usesocketio.emit('chat', message, broadcast=True)inside an event handler correctly uses socketio.emit with event name and broadcast flag.Final Answer:
Use socketio.emit('chat', message, broadcast=True) inside an event handler -> Option AQuick Check:
Broadcast all clients = socketio.emit with broadcast=True [OK]
- Omitting broadcast=True to send to all clients
- Using emit without socketio object for broadcast
- Trying to broadcast via app.run parameters
Ready to prove it?
Pass the test and this pattern moves unknown
