Send WebSocket message from Flask view

2.8k views Asked by At

I'm trying to make a Flask app that uses WebSockets. The example from Flask-sockets works but how would I send a message from a regular view?

Similarly to how Flask-SocketIO use .emit() and .send()-methods.

In the example below (from the Flask-Sockets example) I would for instance like to be able to broadcast a message from the hello-view.

from flask import Flask
from flask_sockets import Sockets


app = Flask(__name__)
sockets = Sockets(app)


@sockets.route('/echo')
def echo_socket(ws):
    while not ws.closed:
        message = ws.receive()
        ws.send(message)


@app.route('/')
def hello():
    # How can I send a WebSocket message from here?
    return 'Hello World!'


if __name__ == "__main__":
    from gevent import pywsgi
    from geventwebsocket.handler import WebSocketHandler
    server = pywsgi.WSGIServer(('', 5000), app, handler_class=WebSocketHandler)
    server.serve_forever()
1

There are 1 answers

0
umut On BEST ANSWER

You can use a global socket list of all client. Traverse all list and send message to all ws instance.

Example code;

from flask import Flask, render_template
from flask_sockets import Sockets


app = Flask(__name__)
sockets = Sockets(app)

ws_list = []

@sockets.route('/echo')
def echo_socket(ws):
    ws_list.append(ws)
    while not ws.closed:
        message = ws.receive()
        ws.send(message)


@app.route('/')
def hello():
    # How can I send a WebSocket message from here?
    return render_template('index.html')


@app.route('/send_message_to_all_client')
def broadcast():

    for ws in ws_list:
        if not ws.closed:
            ws.send("broadcast message")
        else:
            # Remove ws if connection closed.
            ws_list.remove(ws)

    return "ok"

if __name__ == "__main__":
    from gevent import pywsgi
    from geventwebsocket.handler import WebSocketHandler
    server = pywsgi.WSGIServer(('', 5000), app, handler_class=WebSocketHandler)
    server.serve_forever()