How to use the urllib3.exceptions.ProtocolError function in urllib3

To help you get started, we’ve selected a few urllib3 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 demisto / demisto-sdk / demisto_sdk / commands / lint / lint_manager.py View on Github external
logger.debug("Test mandatory modules successfully collected")
        except git.GitCommandError as e:
            print_error(
                "Unable to get test-modules demisto-mock.py etc - Aborting! corrupt repository of pull from master")
            logger.error(f"demisto-sdk-unable to get mandatory test-modules demisto-mock.py etc {e}")
            sys.exit(1)
        except (requests.exceptions.ConnectionError, urllib3.exceptions.NewConnectionError) as e:
            print_error("Unable to get mandatory test-modules demisto-mock.py etc - Aborting! (Check your internet "
                        "connection)")
            logger.error(f"demisto-sdk-unable to get mandatory test-modules demisto-mock.py etc {e}")
            sys.exit(1)
        # Validating docker engine connection
        docker_client: docker.DockerClient = docker.from_env()
        try:
            docker_client.ping()
        except (requests.exceptions.ConnectionError, urllib3.exceptions.ProtocolError, docker.errors.APIError):
            facts["docker_engine"] = False
            print_warning("Can't communicate with Docker daemon - check your docker Engine is ON - Skipping lint, "
                          "test which require docker!")
            logger.info("demisto-sdk-Can't communicate with Docker daemon")
        logger.debug("Docker daemon test passed")

        return facts
github Instagram-Tools / bot / include / bot.py View on Github external
f["fun"]()
                    count = 0
                    sleep(1 * 60)

                sleep(2 * 60)

            except NoSuchElementException as exc:
                # if changes to IG layout, upload the file to help us locate the change
                file_path = os.path.join(gettempdir(), '{}.html'.format(time.strftime('%Y%m%d-%H%M%S')))
                with open(file_path, 'wb') as fp:
                    fp.write(self.browser.page_source.encode('utf8'))
                print('{0}\nIf raising an issue, please also upload the file located at:\n{1}\n{0}'.format(
                    '*' * 70, file_path))
                # full stacktrace when raising Github issue
                self.logger.exception(exc)
            except (ConnectionRefusedError, RemoteDisconnected, ProtocolError,
                    MaxRetryError, AttributeError) as exc:
                return self.try_again(count, exc)
            except Exception as exc:
                if 'RemoteDisconnected' in str(exc):
                    return self.try_again(count, exc)

                self.logger.error("Excepiton in act(): %s \n %s" % (exc, traceback.format_exc()))
                raise
github psf / requests / requests / adapters.py View on Github external
try:
            resp = conn.urlopen(
                method=request.method,
                url=url,
                body=request.body,
                headers=request.headers,
                redirect=False,
                assert_same_host=False,
                preload_content=False,
                decode_content=False,
                retries=self.max_retries,
                timeout=timeout,
                chunked=chunked
            )

        except (ProtocolError, socket.error) as err:
            raise ConnectionError(err, request=request)

        except MaxRetryError as e:
            if isinstance(e.reason, ConnectTimeoutError):
                # TODO: Remove this in 3.0.0: see #2811
                if not isinstance(e.reason, NewConnectionError):
                    raise ConnectTimeout(e, request=request)

            if isinstance(e.reason, ResponseError):
                raise RetryError(e, request=request)

            if isinstance(e.reason, _ProxyError):
                raise ProxyError(e, request=request)

            if isinstance(e.reason, _SSLError):
                # This branch is for urllib3 v1.22 and later.
github urllib3 / urllib3 / urllib3 / exceptions.py View on Github external
class InsecureRequestWarning(SecurityWarning):
    "Warned when making an unverified HTTPS request."
    pass


class SystemTimeWarning(SecurityWarning):
    "Warned when system time is suspected to be wrong"
    pass


class InsecurePlatformWarning(SecurityWarning):
    "Warned when certain SSL configuration is not available on a platform."
    pass


class ResponseNotChunked(ProtocolError, ValueError):
    "Response needs to be chunked in order to read it as chunks."
    pass
github openstack / dragonflow / dragonflow / db / drivers / etcd_db_driver.py View on Github external
raise exceptions.ReadTimeoutError(
                self._pool, None, 'Read timed out.')

        except connection.BaseSSLError as e:
            # FIXME: Is there a better way to differentiate between SSLErrors?
            if 'read operation timed out' not in str(e):  # Defensive:
                # This shouldn't happen but just in case we're missing an edge
                # case, let's avoid swallowing SSL errors.
                raise

            raise exceptions.ReadTimeoutError(
                self._pool, None, 'Read timed out.')

        except connection.HTTPException as e:
            # This includes IncompleteRead.
            raise exceptions.ProtocolError('Connection broken: %r' % e, e)
    except Exception:
        # The response may not be closed but we're not going to use it anymore
        # so close it now to ensure that the connection is released back to the
        #  pool.
        if self._original_response and not self._original_response.isclosed():
            self._original_response.close()

        # Before returning the socket, close it.  From the server's
        # point of view,
        # this socket is in the middle of handling an SSL handshake/HTTP
        # request so it we were to try and re-use the connection later,
        #  we'd see undefined behaviour.
        #
        # Still return the connection to the pool (it will be
        # re-established next time it is used).
        self._connection.close()
github steemit / steem-python / steembase / http_client.py View on Github external
def call(self,
             name,
             *args,
             **kwargs):
        """ Call a remote procedure in steemd.

        Warnings:

            This command will auto-retry in case of node failure, as well
            as handle node fail-over.

        """

        # tuple of Exceptions which are eligible for retry
        retry_exceptions = (MaxRetryError, ReadTimeoutError,
                            ProtocolError, RPCErrorRecoverable,)

        if sys.version > '3.5':
            retry_exceptions += (json.decoder.JSONDecodeError, RemoteDisconnected,)
        else:
            retry_exceptions += (ValueError,)

        if sys.version > '3.0':
            retry_exceptions += (ConnectionResetError,)
        else:
            retry_exceptions += (HTTPException,)

        tries = 0
        while True:
            try:

                body_kwargs = kwargs.copy()
github NNTin / discord-twitter-bot / bot / main.py View on Github external
print("Twitter stream started.")
    while True:

        def print_error(_error):
            print(
                f"---------Error---------\n"
                f"Known error. Ignore. Nothing you can do.\n"
                f"{_error}\n"
                f"Sleeping for 1 minute then continuing.\n"
                f"-----------------------"
            )
            sleep(600)

        try:
            stream.filter(follow=config["twitter_ids"])
        except urllib3.exceptions.ProtocolError as error:
            print_error(_error=error)
        except ConnectionResetError as error:
            print_error(_error=error)
        except ConnectionError as error:
            print_error(_error=error)
        except requests.exceptions.ConnectionError as error:
            print_error(_error=error)
        except Exception as error:
            print(
                f"---------Error---------\n"
                f"unknown error\n"
                f"You've found an error. Please contact the owner (https://discord.gg/JV5eUB) "
                f"and send him what follows below:\n"
                f"{error}\n"
                f"{config}\n"
                f"Sleeping for 5 minute then continuing.\n"
github Azure / azure-sdk-for-python / sdk / core / azure-core / azure / core / pipeline / transport / _requests_trio.py View on Github external
headers=request.headers,
                        data=request.data,
                        files=request.files,
                        verify=kwargs.pop('connection_verify', self.connection_config.verify),
                        timeout=kwargs.pop('connection_timeout', self.connection_config.timeout),
                        cert=kwargs.pop('connection_cert', self.connection_config.cert),
                        allow_redirects=False,
                        **kwargs),
                    limiter=trio_limiter)

        except urllib3.exceptions.NewConnectionError as err:
            error = ServiceRequestError(err, error=err)
        except requests.exceptions.ReadTimeout as err:
            error = ServiceResponseError(err, error=err)
        except requests.exceptions.ConnectionError as err:
            if err.args and isinstance(err.args[0], urllib3.exceptions.ProtocolError):
                error = ServiceResponseError(err, error=err)
            else:
                error = ServiceRequestError(err, error=err)
        except requests.RequestException as err:
            error = ServiceRequestError(err, error=err)

        if error:
            raise error

        return TrioRequestsTransportResponse(request, response, self.connection_config.data_block_size)
github sjdv1982 / seamless / seamless / graphs / docker_transformer / executor.py View on Github external
* Command
*************************************************
{}
*************************************************
Exit code: {}
*************************************************
* Standard error
*************************************************
{}
*************************************************
""".format(docker_command, exit_status, stderr)) from None
        except ConnectionError as exc:
            msg = "Unknown connection error"
            if len(exc.args) == 1:
                exc2 = exc.args[0]
                if isinstance(exc2, ProtocolError):
                    if len(exc2.args) == 2:
                        a, exc3 = exc2.args
                        msg = "Docker gave an error: {}: {}".format(a, exc3)
                        if a.startswith("Connection aborted"):
                            if isinstance(exc3, FileNotFoundError):
                                if len(exc3.args) == 2:
                                    a1, a2 = exc3.args
                                    if a1 == 2 or a2 == "No such file or directory":
                                        msg = "Cannot connect to Docker; did you expose the Docker socket to Seamless?"
            raise SeamlessTransformationError(msg) from None

        if not os.path.exists(resultfile):
            msg = """
Docker transformer exception
============================
github pypa / pipenv / pipenv / vendor / requests / adapters.py View on Github external
r = low_conn.getresponse()

                    resp = HTTPResponse.from_httplib(
                        r,
                        pool=conn,
                        connection=low_conn,
                        preload_content=False,
                        decode_content=False
                    )
                except:
                    # If we hit any problems here, clean up the connection.
                    # Then, reraise so that we can handle the actual exception.
                    low_conn.close()
                    raise

        except (ProtocolError, socket.error) as err:
            raise ConnectionError(err, request=request)

        except MaxRetryError as e:
            if isinstance(e.reason, ConnectTimeoutError):
                # TODO: Remove this in 3.0.0: see #2811
                if not isinstance(e.reason, NewConnectionError):
                    raise ConnectTimeout(e, request=request)

            if isinstance(e.reason, ResponseError):
                raise RetryError(e, request=request)

            if isinstance(e.reason, _ProxyError):
                raise ProxyError(e, request=request)

            if isinstance(e.reason, _SSLError):
                # This branch is for urllib3 v1.22 and later.