Python Flask SocketIO broadcasting outside of @soc

2019-07-08 02:29发布

I'm trying to send a broadcast when an outside value changes. Camonitor calls the callback when the value changes, and I want to notify all connected clients that the value has changed and they need to refresh.

from flask import Flask
from epics import caget, caput, camonitor
from flask_socketio import SocketIO, emit

app = Flask(__name__)
socketio = SocketIO(app)

@socketio.on('connect')
def local_client_connect():
    print "Client connected"


def update_image_data(pvname, value, **kw):
    # broadcast event
    print "Sending broadcast"
    socketio.emit('newimage')


if __name__ == "__main__":
    # start listening for record changes
    camonitor("13SIM1:cam1:NumImagesCounter_RBV", writer=None, callback=update_image_data)
    socketio.run(app, debug=True)

My callback function is successfully called when the value changes, but the broadcast doesn't work. If I move the socketio.emit to local_client_connect, it works.

EDIT: It seems to be a known issue https://github.com/miguelgrinberg/Flask-SocketIO/pull/213

1条回答
Juvenile、少年°
2楼-- · 2019-07-08 03:08

Yes, this is a known issue, but it has a very simple workaround:

def update_image_data(pvname, value, **kw):
    # broadcast event
    print "Sending broadcast"
    with app.app_context():
        socketio.emit('newimage')
查看更多
登录 后发表回答