How can I send a message from a flask route to a socket using flask-socketio How can I send a message from a flask route to a socket using flask-socketio flask flask

How can I send a message from a flask route to a socket using flask-socketio


I'm going to describe how to solve this using Flask-SocketIO beta version 1.0b1. You can also do this with the 0.6 release, but it is a bit more complicated, the 1.0 release makes addressing individual clients easier.

Each client of a socket connection gets assigned a session id that uniquely identifies it, the so called sid. Within a socket function handler, you can access it as request.sid. Also, upon connection, each client is assigned to a private room, named with the session id.

I assume the metadata that you receive with the callback allows you to identify the user. What you need is to obtain the sid of that user. Once you have it, you can send your alert to the corresponding room.

Example (with some hand-waving regarding how you attach a sid to an address):

@app.route('/callback/<address>')def callback(address):    sid = get_sid_from_address(address)    socketio.send('payment seen on blockchain', room=sid)@socketio.on('address')def socketlisten(address):    associate_address_with_sid(address, request.sid)