How to emit websocket message from outside a websocket endpoint? How to emit websocket message from outside a websocket endpoint? flask flask

How to emit websocket message from outside a websocket endpoint?


Quoting from Miguel Grinberg's response on an open issue page on the Flask-SocketIO GitHub:

When you want to emit from a regular route you have to use socketio.emit(), only socket handlers have the socketio context necessary to call the plain emit().

So as an example:

from flask_socketio import SocketIOapp = Flask(__name__)app.config.from_object('config')socketio = SocketIO(app)@app.route('/doc', methods=['POST'])def postDoc():    saveDocument(request.files['file'], g.user.id)    socketio.emit('my response', {'data': 'A NEW FILE WAS POSTED'}, room=current_user.id)    return jsonify({'id': str(doc.id)})