I'm working with tornado and websockets(sockjs) and having trouble while handling incoming messages, getting around this specific case which is that of a circular class reference. The issue is not related to websockets per se, but essentially the cyclicity.
Here's the file which defines the class Socket
for handing incoming messages, it also defines the class Async
which needs the class Socket
. on_message
is triggered when a message is received from the client :
from logicmodule import Logic
class Async(object):
def notify_user(self, *args):
print("Notifying user!")
Socket.send_message("ASYNC CALLBACK: notify_user ARGS: {:}\n".format(args))
async = Async()
logic = Logic(async)
class Socket(SockJSConnection):
clients = set()
def on_open(self, request):
print("Opened Connection...")
self.clients.add(self)
def send_message(self, message, operation):
return self.send(json.dumps({
'operation': operation,
'data': message,
}))
def on_message(self, msg):
data = json.loads(msg)
projectData = logic.create_project(data['project_info'])
self.send_message(projectData, data['operation'])
EDIT:
The Logic Class implements one method create_project
, takes the async
class as a parameter whose method notify_user
is called within the create_project
method. notify_user
requires an instance of Socket
class which can be created only on an incoming message in the on_open
method. That instance will be a persistent connection over which the message will be sent back to user in the notify_user
method.
This is may be a easy hack, but I'm new to python. How do I provide an instance of Socket to Async
on an incoming message which has to be given to logic
beforehand ? Please help, thanks!