Python tornado.websocket.WebSocketHandler() Examples

The following are 12 code examples of tornado.websocket.WebSocketHandler(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tornado.websocket , or try the search function .
Example #1
Source File: websocket.py    From jupyter-server-proxy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # since my parent doesn't keep calling the super() constructor,
        # I need to do it myself
        bases = inspect.getmro(type(self))
        assert WebSocketHandlerMixin in bases
        meindex = bases.index(WebSocketHandlerMixin)
        try:
            nextparent = bases[meindex + 1]
        except IndexError:
            raise Exception("WebSocketHandlerMixin should be followed "
                            "by another parent to make sense")

        # undisallow methods --- t.ws.WebSocketHandler disallows methods,
        # we need to re-enable these methods
        def wrapper(method):
            def undisallow(*args2, **kwargs2):
                getattr(nextparent, method)(self, *args2, **kwargs2)
            return undisallow

        for method in ["write", "redirect", "set_header", "set_cookie",
                       "set_status", "flush", "finish"]:
            setattr(self, method, wrapper(method))
        nextparent.__init__(self, *args, **kwargs) 
Example #2
Source File: main.py    From backend with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, application, request, **kwargs):
        super(WebSocketHandler, self).__init__(application, request, **kwargs)
        self.remote_ip = request.headers.get(
            'X-Forwarded-For',
            request.headers.get(
                'X-Real-Ip',
                request.remote_ip))
        application.log('INFO', 'CONNECTION_OPEN', self.remote_ip )

        self.trade_client = None
        self.user_response = None
        self.last_message_datetime = [datetime.now()]
        self.open_orders = {}
        self.md_subscriptions = {}
        self.sec_status_subscriptions = {}
        self.honey_pot_connection = False

        if self.application.is_tor_node( self.remote_ip ):
            self.honey_pot_connection = True
            application.log('INFO', 'BLOCKED_TOR_NODE', self.remote_ip )
            return

        self.trade_client = TradeClient(
            self.application.zmq_context,
            self.application.trade_in_socket,
            self.application.options.trade_pub) 
Example #3
Source File: main.py    From backend with GNU General Public License v2.0 5 votes vote down vote up
def write_message(self, message, binary=False):
        super(WebSocketHandler, self).write_message(message, binary) 
Example #4
Source File: main.py    From backend with GNU General Public License v2.0 5 votes vote down vote up
def close(self, code=None, reason=None):
      self.application.log('DEBUG', self.remote_ip, 'WebSocketHandler.close() invoked' )
      super(WebSocketHandler, self).close() 
Example #5
Source File: proxy.py    From training_results_v0.6 with Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(WebSocketHandler, self).__init__(*args, **kwargs)
        self._init_handler() 
Example #6
Source File: origami.py    From origami-lib with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def check_origin(self, origin):
        """
        Overridden function from WebSocketHandler for CORS policy.
        This ensures that websocket connection can be made from any
        origin.
        """
        return True 
Example #7
Source File: origami.py    From origami-lib with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def open(self):
        """
        A new websocket connection is opened.
        Overridden function from WebSocketHandler

        This method resets the global connection variables.
        """
        self.__reset_connection() 
Example #8
Source File: origami.py    From origami-lib with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def on_message(self, message):
        """
        Got a messege from the websocket connection.
        Overridden method from WebSocketHandler.

        This method recieves the message from the websocket connection and
        validates the message. If the message is validated it extracts the
        data from the message and pass it as an argument to the function
        registered corresponding to the users socket-id. The returned value
        from the function is sent back to user as a response.

        Args:
            message: message from the websocket connection. \
                This message is what we got from the websocket, first we need \
                to validate it and then extract the required matter from it \
                which will then be used by the registered function.
        """
        data = self._validate_message(message)
        if data:
            out_msg = self.active_connection["func"](
                *self.active_connection["arguments"], message=data)
            try:
                # Send the out_msg returned from the function.
                if isinstance(out_msg, dict):
                    json_resp = json.dumps(out_msg)
                    self.write_message(json_resp)
                elif utils.check_if_string(out_msg):
                    self.write_message(out_msg)
                    # self._origmai_send_data(
                    #     "ws_data", out_msg, socketId=self.connection_id)
                else:
                    print(
                        "A persistent connection can only return a python dict \
                        or string")
            except Exception:
                pass 
Example #9
Source File: handlers.py    From jupyter_http_over_ws with Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
    websocket.WebSocketHandler.__init__(self, *args, **kwargs)
    handlers.IPythonHandler.__init__(self, *args, **kwargs)

    ca_certs = None
    if self.request.protocol == 'https':
      ca_certs = self.config.get('NotebookApp', {}).get('certfile')
      if not ca_certs:
        raise ValueError('HTTPS requires the NotebookApp.certfile setting to '
                         'be present.')
    self.ca_certs = ca_certs 
Example #10
Source File: proxy.py    From incubator-tvm with Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(WebSocketHandler, self).__init__(*args, **kwargs)
        self._init_handler() 
Example #11
Source File: proxy.py    From training_results_v0.6 with Apache License 2.0 4 votes vote down vote up
def __init__(self,
                 sock,
                 listen_port,
                 web_port,
                 timeout_client,
                 timeout_server,
                 tracker_addr,
                 index_page=None,
                 resource_files=None):
        assert ProxyServerHandler.current is None
        ProxyServerHandler.current = self
        if web_port:
            handlers = [
                (r"/ws", WebSocketHandler),
            ]
            if index_page:
                handlers.append(
                    (r"/", RequestHandler, {"file_path": index_page, "rpc_web_port": web_port}))
                logging.info("Serving RPC index html page at http://localhost:%d", web_port)
            resource_files = resource_files if resource_files else []
            for fname in resource_files:
                basename = os.path.basename(fname)
                pair = (r"/%s" % basename, RequestHandler, {"file_path": fname})
                handlers.append(pair)
                logging.info(pair)
            self.app = tornado.web.Application(handlers)
            self.app.listen(web_port)
        self.sock = sock
        self.sock.setblocking(0)
        self.loop = ioloop.IOLoop.current()
        def event_handler(_, events):
            self._on_event(events)
        self.loop.add_handler(
            self.sock.fileno(), event_handler, self.loop.READ)
        self._client_pool = {}
        self._server_pool = {}
        self.timeout_alloc = 5
        self.timeout_client = timeout_client
        self.timeout_server = timeout_server
        # tracker information
        self._listen_port = listen_port
        self._tracker_addr = tracker_addr
        self._tracker_conn = None
        self._tracker_pending_puts = []
        self._key_set = set()
        self.update_tracker_period = 2
        if tracker_addr:
            logging.info("Tracker address:%s", str(tracker_addr))
            def _callback():
                self._update_tracker(True)
            self.loop.call_later(self.update_tracker_period, _callback)
        logging.info("RPCProxy: Websock port bind to %d", web_port) 
Example #12
Source File: proxy.py    From incubator-tvm with Apache License 2.0 4 votes vote down vote up
def __init__(self,
                 sock,
                 listen_port,
                 web_port,
                 timeout_client,
                 timeout_server,
                 tracker_addr,
                 index_page=None,
                 resource_files=None):
        assert ProxyServerHandler.current is None
        ProxyServerHandler.current = self
        if web_port:
            handlers = [
                (r"/ws", WebSocketHandler),
            ]
            if index_page:
                handlers.append(
                    (r"/", RequestHandler, {"file_path": index_page, "rpc_web_port": web_port}))
                logging.info("Serving RPC index html page at http://localhost:%d", web_port)
            resource_files = resource_files if resource_files else []
            for fname in resource_files:
                basename = os.path.basename(fname)
                pair = (r"/%s" % basename, RequestHandler, {"file_path": fname})
                handlers.append(pair)
                logging.info(pair)
            self.app = tornado.web.Application(handlers)
            self.app.listen(web_port)
        self.sock = sock
        self.sock.setblocking(0)
        self.loop = ioloop.IOLoop.current()
        def event_handler(_, events):
            self._on_event(events)
        self.loop.add_handler(
            self.sock.fileno(), event_handler, self.loop.READ)
        self._client_pool = {}
        self._server_pool = {}
        self.timeout_alloc = 5
        self.timeout_client = timeout_client
        self.timeout_server = timeout_server
        # tracker information
        self._listen_port = listen_port
        self._tracker_addr = tracker_addr
        self._tracker_conn = None
        self._tracker_pending_puts = []
        self._key_set = set()
        self.update_tracker_period = 2
        if tracker_addr:
            logging.info("Tracker address:%s", str(tracker_addr))
            def _callback():
                self._update_tracker(True)
            self.loop.call_later(self.update_tracker_period, _callback)
        logging.info("RPCProxy: Websock port bind to %d", web_port)