2

I am trying to listen to new socketIO connections on the user's id namespace. The user ID is stored in the flask session object.

 @socketio.on('connect', namespace=session['userId'])
 def test_connect():
    emit('newMessage')

This code is producing the following error:

raise RuntimeError('working outside of request context')

How can I get the above connect listener to run within the request context?

Thanks!

Jakobovski
  • 3,203
  • 1
  • 31
  • 38

1 Answers1

2

Unfortunately this cannot be done, because namespaces aren't dynamic, you have to use a static string as a namespace.

The idea of the namespace in SocketIO is not to add information about the connection, but to allow the client to open more than one individual channel with the server. Namespaces allow the SocketIO protocol to multiplex all these channels into a single physical connection.

What you want to do is to provide an input argument of the connection into the server. For that, just add the value to your payload:

@socketio.on('connect', namespace='/chat')
def test_connect():
    userid = session['userId']
    # ...
Miguel Grinberg
  • 65,299
  • 14
  • 133
  • 152