You have two options:
Import the
socketio
object into the separate module you put the views in. As long as you then import that module after creating thesocketio
object things work. So in yourmain
module you have:from flask import Flask from flask.ext.socketio import SocketIO, emit, send app = Flask(__name__) socketio = SocketIO(app) import socket_views if __name__ == '__main__': socketio.run(app)
and in
socket_views.py
you have:from main import socketio @socketio.on('connect', namespace='/namespaceOne') def test_connectOne(): print('new connection') @socketio.on('connect', namespace='/namespaceTwo') def test_connectTwo(): print('new connection')
See the Larger Application chapter of the Flask documentation; specifically the Circular Imports section.
Apply the
@socketio.on()
decorator 'manually'; the@expression
syntax is just syntactic sugar to apply a callable to a function. Since the@socketio.on()
decorator only registers you can simply put your views as regular, un-decorated functions in the separate module then register them after importing with:from socket_views import test_connectOne, test_connectTwo socketio.on('connect', namespace='/namespaceOne')(test_connectOne) socketio.on('connect', namespace='/namespaceTwo')(test_connectTwo)