How to use the websockets.exceptions.InvalidStatusCode function in websockets

To help you get started, we’ve selected a few websockets examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github aaugustin / websockets / tests / test_auth.py View on Github external
def test_basic_auth_unsupported_credentials(self):
        with self.assertRaises(InvalidStatusCode) as raised:
            self.start_client(extra_headers={"Authorization": "Digest ..."})
        self.assertEqual(raised.exception.status_code, 401)
github aaugustin / websockets / tests / test_client_server.py View on Github external
def assert_client_raises_code(self, status_code):
        with self.assertRaises(InvalidStatusCode) as raised:
            self.start_client()
        self.assertEqual(raised.exception.status_code, status_code)
github ShichaoMa / apistellar / tests / test_bases / test_websocket.py View on Github external
async def test_websocket_not_found(self, server):
        with pytest.raises(InvalidStatusCode):
            async with websockets.connect(
                    f"ws://127.0.0.1:{server.port}/websocket/not/found") as ws:
                    assert await ws.recv()
github aaugustin / websockets / tests / test_auth.py View on Github external
def test_basic_auth_missing_credentials(self):
        with self.assertRaises(InvalidStatusCode) as raised:
            self.start_client()
        self.assertEqual(raised.exception.status_code, 401)
github gnachman / iTerm2 / api / library / python / iterm2 / iterm2 / connection.py View on Github external
while not done:
            try:
                async with websockets.connect(
                        _uri(),
                        ping_interval=None,
                        extra_headers=_headers(),
                        subprotocols=_subprotocols()) as websocket:
                    done = True
                    self.websocket = websocket
                    # pylint: disable=broad-except
                    try:
                        return await coro(self)
                    except Exception as _err:
                        traceback.print_exc()
                        sys.exit(1)
            except websockets.exceptions.InvalidStatusCode as exception:
                if exception.status_code == 406:
                    print("This version of the iterm2 module is too old " +
                          "for the current version of iTerm2. Please upgrade.")
                    sys.exit(1)
                raise
            except websockets.exceptions.InvalidMessage:
                # This is a temporary workaround for this issue:
                #
                # https://gitlab.com/gnachman/iterm2/issues/7681#note_163548399
                # https://github.com/aaugustin/websockets/issues/604
                #
                # I'm leaving the print statement in because I'm worried this
                # might have unexpected consequences, as InvalidMessage is
                # certainly not very specific.
                print("websockets.connect failed with InvalidMessage. " +
                      "Retrying.")
github oliver-zehentleitner / unicorn-binance-websocket-api / unicorn_binance_websocket_api / unicorn_binance_websocket_api_connection.py View on Github external
logging.error("BinanceWebSocketApiConnection->await._conn.__aenter__(" + str(self.stream_id) + ", " +
                          str(self.channels) + ", " + str(self.markets) + ")" + " - ConnectionResetError - " +
                          str(error_msg))
        except OSError as error_msg:
            logging.error("BinanceWebSocketApiConnection->await._conn.__aenter__(" + str(self.stream_id) + ", " +
                          str(self.channels) + ", " + str(self.markets) + ")" + " - OSError "
                          "- " + str(error_msg))
        except socket.gaierror as error_msg:
            logging.critical("BinanceWebSocketApiConnection->await._conn.__aenter__(" + str(self.stream_id) + ", " +
                             str(self.channels) + ", " + str(self.markets) + ")" + " - No internet connection? "
                             "- " + str(error_msg))
            self.handler_binance_websocket_api_manager.stream_is_crashing(self.stream_id, (str(error_msg) +
                                                                          " - No internet connection?"))
            self.handler_binance_websocket_api_manager.set_restart_request(self.stream_id)
            sys.exit(1)
        except websockets.exceptions.InvalidStatusCode as error_msg:
            if "Status code not 101: 414" in str(error_msg):
                self.handler_binance_websocket_api_manager.stream_is_crashing(self.stream_id, str(error_msg) +
                                                                              " --> URI too long? ;)")
                logging.critical("BinanceWebSocketApiConnection->await._conn.__aenter__(" + str(self.stream_id) + ", " +
                                 str(self.channels) + ", " + str(self.markets) + ")" + " - URI Too Long? To many "
                                 "streams in on socket? ;) - " + str(error_msg))
                try:
                    self.handler_binance_websocket_api_manager.websocket_list[self.stream_id].close()
                except KeyError:
                    pass
                sys.exit(1)
            elif "Status code not 101: 400" in str(error_msg):
                logging.error("BinanceWebSocketApiConnection->await._conn.__aenter__(" + str(self.stream_id) + ", " +
                              str(self.channels) + ", " + str(self.markets) + ") " + str(error_msg))
            elif "Status code not 101: 429" in str(error_msg):
                logging.error("BinanceWebSocketApiConnection->await._conn.__aenter__(" + str(self.stream_id) + ", " +
github cs01 / termpair / termpair / share.py View on Github external
ws_id = await _initialize_broadcast(
                cmd, url, ws, stdin_fd, pty_fd, allow_browser_control, secret_key
            )
            with utils.make_raw(stdin_fd):
                await _do_broadcast(
                    pty_fd,
                    stdin_fd,
                    stdout_fd,
                    ws,
                    _get_share_url(url, ws_id, secret_key),
                    open_browser,
                    allow_browser_control,
                    secret_key,
                )
            print(f"You are no longer broadcasting session id {session_id}")
    except websockets.exceptions.InvalidStatusCode as e:
        print(
            f"Failed to connect to {ws_endpoint}. "
            "Check the url and port, and ensure the server is running."
        )
        print(str(e))
github abersheeran / websocks / websocks / client.py View on Github external
async def _create(self) -> None:
        try:
            sock = await websockets.connect(
                self.server, extra_headers={"Authorization": self.get_credentials()}
            )
            self._freepool.add(sock)
        except websockets.exceptions.InvalidStatusCode as e:
            logger.error(str(e))
github kayagoban / shadowlands / shadowlands / eth_node.py View on Github external
def poll(self):
        logging.debug("eth_node poll()")
        try: 
            if self._w3.isConnected():
                self._update_status()

        except (ConnectionError, AttributeError, UnhandledRequest, Timeout, InvalidStatusCode, ConnectionClosed, TimeoutError, OSError, StaleBlockchain, ValueError) as e:
            logging.info("eth_node poll: {}".format(traceback.format_exc()))
            self.connect_config_default() or self.connect_w3_local()
github kayagoban / shadowlands / shadowlands / tui / effects / network_options.py View on Github external
def _attempt_connection(self, fn_name, arg=None):
        fn = self._interface.node.__getattribute__(fn_name)
        self._interface.node.thread_shutdown = True
        self._interface.node.heartbeat_thread.join()
        self._interface.node.thread_shutdown = False
        try:
            #debug(); pdb.set_trace()
            if arg:
                return fn(arg)
            else:
                return fn()
        except StaleBlockchain:
            self._scene.add_effect( MessageDialog(self._screen, "Stale blockchain on selected Node"))
            return
        except (AttributeError, UnhandledRequest, InvalidStatusCode, ConnectionClosed, TimeoutError, OSError) as e: #Timeout
            self._scene.add_effect( MessageDialog(self._screen, "Could not connect to node ({})".format(str(e.__class__))))
            return
 
        self._interface.node.start_heartbeat_thread()