mirror of
https://github.com/avatao-content/baseimage-tutorial-framework
synced 2024-11-22 15:41:32 +00:00
49 lines
1.3 KiB
Python
49 lines
1.3 KiB
Python
import json
|
|
import logging
|
|
|
|
from tornado.websocket import WebSocketHandler
|
|
|
|
from .tfw_router import TFWRouter
|
|
|
|
LOG = logging.getLogger(__name__)
|
|
|
|
|
|
class ZMQWebSocketRouter(WebSocketHandler):
|
|
# pylint: disable=abstract-method,attribute-defined-outside-init
|
|
instances = set()
|
|
|
|
def initialize(self, **kwargs):
|
|
self._listener = kwargs['listener']
|
|
self.tfw_router = TFWRouter(self.send_to_zmq, self.send_to_websockets)
|
|
|
|
def send_to_zmq(self, message):
|
|
self._listener.send_message(message)
|
|
|
|
@classmethod
|
|
def send_to_websockets(cls, message):
|
|
for instance in cls.instances:
|
|
instance.write_message(message)
|
|
|
|
def prepare(self):
|
|
type(self).instances.add(self)
|
|
|
|
def on_close(self):
|
|
type(self).instances.remove(self)
|
|
|
|
def open(self, *args, **kwargs):
|
|
LOG.debug('WebSocket connection initiated!')
|
|
self._listener.register_callback(self.zmq_callback)
|
|
|
|
def zmq_callback(self, message):
|
|
LOG.debug('Received on ZMQ pull socket: %s', message)
|
|
self.tfw_router.route(message)
|
|
|
|
def on_message(self, message):
|
|
message = json.loads(message)
|
|
LOG.debug('Received on WebSocket: %s', message)
|
|
self.tfw_router.route(message)
|
|
|
|
# much secure, very cors, wow
|
|
def check_origin(self, origin):
|
|
return True
|