WebSocket events handling lets your Flask app talk to users instantly. It helps send and receive messages without waiting for page reloads.
WebSocket events handling in Flask
from flask import Flask from flask_socketio import SocketIO, send, emit app = Flask(__name__) socketio = SocketIO(app) @socketio.on('event_name') def handle_event(data): # code to handle event pass if __name__ == '__main__': socketio.run(app)
Use @socketio.on('event_name') to listen for WebSocket events.
Inside the handler, use send() or emit() to reply.
@socketio.on('message') def handle_message(msg): send(f'Received: {msg}')
@socketio.on('json') def handle_json(json_data): emit('response', {'data': 'Got your JSON!'})
@socketio.on('connect') def on_connect(): print('Client connected')
This Flask app listens for 'message' events from clients. When a message arrives, it prints it on the server and sends a reply back to the client.
from flask import Flask from flask_socketio import SocketIO, send app = Flask(__name__) socketio = SocketIO(app) @socketio.on('message') def handle_message(msg): print(f'Received message: {msg}') send(f'Server says: {msg}') if __name__ == '__main__': socketio.run(app, debug=True)
Remember to run your Flask app with socketio.run(app) instead of app.run().
Use send() for simple messages and emit() for custom events.
WebSocket events let your app be interactive and real-time without page reloads.
WebSocket events let Flask apps send and receive messages instantly.
Use @socketio.on('event') to handle events and send() or emit() to reply.
This is great for chat, live updates, notifications, and games.
Practice
@socketio.on('message') do in a Flask app using WebSocket?Solution
Step 1: Understand the decorator role
The@socketio.on('message')decorator registers a function to handle incoming WebSocket events named 'message'.Step 2: Differentiate from other actions
Sending messages or closing connections are done by other functions, not by this decorator.Final Answer:
It listens for incoming WebSocket messages with the event name 'message'. -> Option CQuick Check:
Decorator for event handling = C [OK]
- Confusing event handler with sending messages
- Thinking it closes connections
- Assuming it initializes the app
Solution
Step 1: Identify the correct function call
In Flask-SocketIO, use the importedsend()function inside handlers to reply to the sender client.Step 2: Check syntax correctness
A:send('Hello client!')correctly sends to sender. B:socketio.send()sends to all clients. C:emit('Hello client!')uses message as event name without data. D:socketundefined.Final Answer:
send('Hello client!') -> Option BQuick Check:
Use send() to reply to sender [OK]
- Using socketio.send() which sends to all clients
- Malformed emit() call without data
- Using undefined socket object
@socketio.on('chat')
def handle_chat(msg):
print('Received:', msg)
send('Echo: ' + msg)What will be printed and sent if the client sends the message 'Hi'?
Solution
Step 1: Analyze the print statement
The function prints 'Received: ' plus the message, so it prints 'Received: Hi'.Step 2: Analyze the send() call
The send() function sends the string 'Echo: ' plus the message back to the client, so it sends 'Echo: Hi'.Final Answer:
Prints 'Received: Hi' and sends 'Echo: Hi' back to the client. -> Option DQuick Check:
Print then send echo message = D [OK]
- Mixing print output with sent message
- Assuming send() needs event name
- Confusing order of print and send
@socketio.on('update')
def handle_update():
data = request.json
send(data)Solution
Step 1: Understand request context in WebSocket
WebSocket handlers do not have HTTP request context, sorequest.jsonis not available and causes an error.Step 2: Check other parts
The decorator has event name, send() can send JSON, and function can have zero parameters if no message expected.Final Answer:
Using request.json inside WebSocket handler causes an error. -> Option AQuick Check:
request.json not available in WebSocket handlers [OK]
- Assuming HTTP request context exists in WebSocket
- Thinking send() can't send JSON
- Believing function must have parameters always
Solution
Step 1: Understand broadcasting options
To send to all except sender, useemit()withbroadcast=trueandinclude_self=false.Step 2: Check each option
B:send(data, broadcast=true, include_self=true)includes sender. C:emit('broadcast', data, broadcast=true, include_self=true)includes sender. D:send(data, include_self=false)lacks broadcast flag. A correctly excludes sender.Final Answer:
emit('broadcast', data, broadcast=true, include_self=false) -> Option AQuick Check:
Broadcast exclude sender = emit with include_self=false [OK]
- Using send() incorrectly for targeted broadcast
- Setting include_self=true which includes sender
- Missing broadcast=true flag
Ready to prove it?
Pass the test and this pattern moves unknown
