예제 #1
0
class BaseWebSocketHandler(tornado.websocket.WebSocketHandler):

    def __init__(self, application, request, **kwargs):
        tornado.websocket.WebSocketHandler.__init__(self, application, request,
                                                    **kwargs)
        """
        Instantiate an instance-scoped pubsub to handle websocket
        event subscriptions. Allow websocket handlers to treat messages
        like events, registering with on:

        self.on('frame:update', self._handle_event)

        Which would get triggered when an evented 'frame:update'
        message comes over the pipe
        """
        self.ps = MicroPubSub()

    @property
    def db(self):
        """A connection to the PostgreSQL database."""
        return self.application.db

    @property
    def pubsub(self):
        """Access to the application-wide pubsub system."""
        return self.application.pubsub

    def on_message(self, message):
        """
        Extract event name and data from message,
        call corresponding event handler.
        """
        message = json_decode(message)
        event = message['name']
        data = message['data']
        self.ps.publish(event, data=data)

    def on(self, event, callback):
        """
        Subscribe to some event, presumably coming from the websocket message
        """
        self.ps.subscribe(event, callback)

    def send(self, event, data=None):
        """
        Send an "evented" message out to the websocket client,
        i.e. in the form:
        {
            'name': 'some:event',
            'data': {
                'some': 'data',
                'thinga': 'mabob'
            }
        }
        """
        message = dumps({'name': event, 'data': data})
        self.write_message(message)
예제 #2
0
    def __init__(self, application, request, **kwargs):
        tornado.websocket.WebSocketHandler.__init__(self, application, request,
                                                    **kwargs)
        """
        Instantiate an instance-scoped pubsub to handle websocket
        event subscriptions. Allow websocket handlers to treat messages
        like events, registering with on:

        self.on('frame:update', self._handle_event)

        Which would get triggered when an evented 'frame:update'
        message comes over the pipe
        """
        self.ps = MicroPubSub()