简体   繁体   中英

Flask-socketio, emit an event to another namespace

I am using Flask-socketio ( http://flask-socketio.readthedocs.org/en/latest/ ).

I am currently getting a

KeyError: '/local'

when using this in events.py. Note the differing namespaces:

@socketio.on('connect', namespace='/photo')
def client_connect():
    emit('event', { 'type': 'client_connect' }, namespace='/local')

Using Flask-socketio is it possible to emit to a separate namespace to that which the event occurred on? The documentation seems to suggest so, but I can't workout why I keep getting the KeyError.

EDIT: Thanks @Miguel for your proposed answer, I have tried again (after a long time away from the project) but still get a keyerror with the below:

@socketio.on('connect', namespace='/local')
def local_client_connect():
    print ('Local client connected.')

@socketio.on('connect', namespace='/photo')
def client_connect():
    print ('Client connected.')
    send('client_connect', namespace='/local')

When I run the app I see the printed 'Local client connected.' and only then do I allow a client to access the /photo route. I see 'Client connected' printed and then of course the keyerror.

I have upgraded flask-socketio to 0.4.2.

Best

Andrew

You need to have at least one handler on the second namespace. For example:

@socketio.on('connect', namespace='/local')
def local_client_connect():
    pass

Then Flask-SocketIO will know about /local and will be able to emit messages to it.

I had same problems and solved like this.

@socketio.on('connect', namespace='/photo')
def client_connect():
    socketio.emit('event', { 'type': 'client_connect' }, namespace='/local')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM