Search code examples
pythonpython-3.xflasksocket.ioflask-socketio

TypeError while joining a room with Flask-SocketIO 5.0.1


I am trying to set up a web-app in Python using Flask, having multiple rooms for different users, however using join_room provided by Flask-SocketIO and executing the script this error is returned:

Exception in thread Thread-10:
Traceback (most recent call last):
  File "D:\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner
    self.run()
  File "D:\Python\Python39\lib\threading.py", line 892, in run
    self._target(*self._args, **self._kwargs)
  File "D:\Python\Python39\lib\site-packages\socketio\server.py", line 688, in _handle_event_internal
    r = server._trigger_event(data[0], namespace, sid, *data[1:])
  File "D:\Python\Python39\lib\site-packages\socketio\server.py", line 712, in _trigger_event
    return self.handlers[namespace][event](*args)
  File "D:\Python\Python39\lib\site-packages\flask_socketio\__init__.py", line 283, in _handler
    return self._handle_event(handler, message, namespace, sid,
  File "D:\Python\Python39\lib\site-packages\flask_socketio\__init__.py", line 751, in _handle_event
    ret = handler(*args)
  File "D:\master-thesis\safety-detector\server.py", line 30, in join_room
    join_room(roomId)
  File "D:\master-thesis\safety-detector\server.py", line 28, in join_room
    roomId = data['roomId']
TypeError: string indices must be integers

If I comment out join_room(roomId) the assignment for camId works as expected, so I don't know why this error happens.

Backend code:

@socketio.on('connect')
def connection():
    @socketio.on('join-room')
    def join_room(data):
        roomId = data['roomId']
        camId = data['camId']
        join_room(roomId)
        emit('cam-connected', {'camId': camId}, broadcast=True)
        @socketio.on('disconnect')
        def on_disconnect():
            leave_room(roomId)
            emit('cam-disconnected', {'camId': camId}, broadcast=True)

Solution

  • You have a function named join_room() in your code, which is shadowing the join_room() function from Flask-SocketIO.

    You also have a very strange structure for your Socket.IO handlers with inner functions that is not likely to work (or maybe the indentation got messed up when you copy/pasted the code in your question?). Try something like this:

    @socketio.on('connect')
    def connection():
        pass
    
    @socketio.on('join-room')
    def my_join_room(data):      # <--- rename this to something other than join_room
        roomId = data['roomId']
        camId = data['camId']
        join_room(roomId)
        emit('cam-connected', {'camId': camId}, broadcast=True)
    
    @socketio.on('disconnect')
    def on_disconnect():
        leave_room(roomId)
        emit('cam-disconnected', {'camId': camId}, broadcast=True)