4

I'm making a new application with Flask and socketio. The code simplified is like this:

socketio = SocketIO(app)

@socketio.on('connect', namespace='/test')
def test_connect():
    print('Client connected')
    emit('my response', {'data': 'User Connected'}, broadcast = True)


if __name__ == '__main__':
    socketio.run(app, '0.0.0.0', 8080)

I'm not sure how could I import the "handler: @socketio.on('connect', namespace='/test')" from another class so I don't overload the main class.

I guess Blueprints could be a solution, but I've only found how to use them with the "routes". I'm not sure if this would work with the sockets.

Could anyone give me a hand? Thanks all

Adrian Garcia
  • 698
  • 9
  • 13

1 Answers1

3

The way you can do this is by moving the socketio.on() functions to a different module. You mention classes, but these are really functions, the way to structure your application is by separating the different parts of it into modules or packages.

Take a look at this example that I created to demonstrate one way to structure a Flask application that uses Flask-SocketIO.

Miguel
  • 56,635
  • 12
  • 113
  • 132