roowilliams
roowilliams

Reputation: 183

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

Upvotes: 5

Views: 10213

Answers (2)

nshuya
nshuya

Reputation: 51

I had same problems and solved like this.

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

Upvotes: 5

Miguel Grinberg
Miguel Grinberg

Reputation: 67479

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.

Upvotes: 5

Related Questions