How to use the urllib3.exceptions.HTTPError 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 urllib3 / urllib3 / test / test_exceptions.py View on Github external
def test_exceptions_with_objects(self):
        assert self.verify_pickling(
            HTTPError('foo'))

        assert self.verify_pickling(
            HTTPError('foo', IOError('foo')))

        assert self.verify_pickling(
            MaxRetryError(HTTPConnectionPool('localhost'), '/', None))

        assert self.verify_pickling(
            LocationParseError('fake location'))

        assert self.verify_pickling(
            ClosedPoolError(HTTPConnectionPool('localhost'), None))

        assert self.verify_pickling(
            EmptyPoolError(HTTPConnectionPool('localhost'), None))
github praekelt / feersum-nlu-api-wrappers / test / test_crf_extractor.py View on Github external
print("Delete specific named loaded CRF entity extractor:")
            api_response = api_instance.crf_entity_extractor_del(instance_name)
            print(" type(api_response)", type(api_response))
            print(" api_response", api_response)
            print()

            print("Vaporise specific named loaded CRF entity extractor:")
            api_response = api_instance.crf_entity_extractor_vaporise(instance_name)
            print(" type(api_response)", type(api_response))
            print(" api_response", api_response)
            print()

        except ApiException as e:
            print("Exception when calling an CRF Entity Extractor operation: %s\n" % e)
            self.assertTrue(False)
        except urllib3.exceptions.HTTPError as e:
            print("Connection HTTPError! %s\n" % e)
            self.assertTrue(False)
github Tencent / GAutomator / GAutomatorAndroid / libs / uiauto / uiautomator.py View on Github external
def wrapper(*args, **kwargs):
                logger.debug("Request start".format(*args))
                URLError = urllib3.exceptions.HTTPError if os.name == "nt" else urllib2.URLError
                try:
                    return _method_obj(*args, **kwargs)
                except (URLError, socket.error, HTTPException) as e:
                    if restart:
                        server.stop()
                        server.start(timeout=30)
                        return _JsonRPCMethod(url, method, timeout, False)(*args, **kwargs)
                    else:
                        raise
                except JsonRPCError as e:
                    if e.code >= ERROR_CODE_BASE - 1:
                        server.stop()
                        server.start()
                        return _method_obj(*args, **kwargs)
                    elif e.code == ERROR_CODE_BASE - 2 and self.handlers['on']:  # Not Found
                        try:
github praekelt / feersum-nlu-api-wrappers / examples / faq_matcher_retrieve.py View on Github external
if sample.label[:20] in response_label_set:
                correct = correct + 1
                print('.', sample.text, ", ", sample.label)
            else:
                print('x', sample.text, ", ", sample.label)
            total = total + 1
        # print(" type(api_response)", type(api_response))
        # print(" api_response", api_response)
        # print()

    print("accuracy =", correct / total)

except ApiException as e:
    print("Exception when calling an FAQ matcher operation: %s\n" % e)
except urllib3.exceptions.HTTPError as e:
    print("Connection HTTPError! %s\n" % e)
github zalando / patroni / patroni / dcs / kubernetes.py View on Github external
def __init__(self, config):
        self._labels = config['labels']
        self._labels[config.get('scope_label', 'cluster-name')] = config['scope']
        self._label_selector = ','.join('{0}={1}'.format(k, v) for k, v in self._labels.items())
        self._namespace = config.get('namespace') or 'default'
        self._role_label = config.get('role_label', 'role')
        config['namespace'] = ''
        super(Kubernetes, self).__init__(config)
        self._retry = Retry(deadline=config['retry_timeout'], max_delay=1, max_tries=-1,
                            retry_exceptions=(KubernetesRetriableException, HTTPException,
                                              HTTPError, socket.error, socket.timeout))
        self._ttl = None
        try:
            k8s_config.load_incluster_config()
        except k8s_config.ConfigException:
            k8s_config.load_kube_config(context=config.get('context', 'local'))

        self.__subsets = None
        use_endpoints = config.get('use_endpoints') and (config.get('patronictl') or 'pod_ip' in config)
        if use_endpoints:
            addresses = [k8s_client.V1EndpointAddress(ip='127.0.0.1' if config.get('patronictl') else config['pod_ip'])]
            ports = []
            for p in config.get('ports', [{}]):
                port = {'port': int(p.get('port', '5432'))}
                port.update({n: p[n] for n in ('name', 'protocol') if p.get(n)})
                ports.append(k8s_client.V1EndpointPort(**port))
            self.__subsets = [k8s_client.V1EndpointSubset(addresses=addresses, ports=ports)]
github koroshiya / batoto-downloader-py / urllib3 / exceptions.py View on Github external
# For pickling purposes.
        return self.__class__, (None, None)


class RequestError(PoolError):
    "Base exception for PoolErrors that have associated URLs."
    def __init__(self, pool, url, message):
        self.url = url
        PoolError.__init__(self, pool, message)

    def __reduce__(self):
        # For pickling purposes.
        return self.__class__, (None, self.url, None)


class SSLError(HTTPError):
    "Raised when SSL certificate fails in an HTTPS connection."
    pass


class ProxyError(HTTPError):
    "Raised when the connection to a proxy fails."
    pass


class DecodeError(HTTPError):
    "Raised when automatic decoding based on Content-Type fails."
    pass


class ProtocolError(HTTPError):
    "Raised when something unexpected happens mid-request/response."
github argoproj / argo-workflows / platform / source / lib / ax / platform / ax_master_manager.py View on Github external
def wait_for_termination(self):
        """
        Waits the termination of the currently running master instance.
        """
        # check if master api server is alive and if not terminate master
        try:
            logger.info("Checking if Master API server is alive...")
            self.check_master_api_server()
            logger.info("Master API server is alive...")
        except Exception as e:
            if isinstance(e, urllib3.exceptions.HTTPError):
                logger.error("Got the following exception while trying to check master api server {}".format(e))
                logger.info("Assuming master is bad and terminating it...")
                self.terminate_master()
                logger.info("Done terminating master")
                return
            else:
                logger.warn("Got the following error from Kubernetes Master API Server {}. Looks like it is alive so ignoring this temporary error".format(e))

        logger.debug("Waiting for master termination signal ...")
        self.master_instance.wait_until_terminated()
        logger.info("Master down!")
github polyaxon / polyaxon / cli / polyaxon / client / utils.py View on Github external
def impersonate(owner, project, run_uuid):
    try:
        response = PolyaxonClient().runs_v1.impersonate_token(owner, project, run_uuid)
        polyaxon_client = PolyaxonClient(token=response.token)
        user = polyaxon_client.users_v1.get_user()
        access_token = AccessTokenConfig(username=user.username, token=response.token)
        create_context_auth(access_token)
    except (ApiException, HTTPError) as e:
        raise PolyaxonClientException(
            "This worker is not allowed to run this job %s." % e
        )
github kylebebak / Requester / deps / requests / adapters.py View on Github external
if isinstance(e.reason, _ProxyError):
                raise ProxyError(e, request=request)

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

            raise ConnectionError(e, request=request)

        except ClosedPoolError as e:
            raise ConnectionError(e, request=request)

        except _ProxyError as e:
            raise ProxyError(e)

        except (_SSLError, _HTTPError) as e:
            if isinstance(e, _SSLError):
                # This branch is for urllib3 versions earlier than v1.22
                raise SSLError(e, request=request)
            elif isinstance(e, ReadTimeoutError):
                raise ReadTimeout(e, request=request)
            else:
                raise

        return self.build_response(request, resp)
github jopcode / whoUR / libs / adminFinder.py View on Github external
print(P+'\n-------------------------')
    print(P+'-A D M I N  F I N D E R -')
    print(P+'-------------------------\n')
    print(B+'[!] Scann in Process...\n')

    with open(dic_adminsPage) as f:
        admin_page_found = []
        admin_page_not_found = 0
        contents = f.readlines()
        print(P+'[+] Please be Patient, This May Take a While\n')
        http = urllib3.PoolManager()
        for content in contents:
            url_request = url_input+'/'+content
            try:
                url = http.request('GET', 'http://'+url_request)
            except urllib3.exceptions.HTTPError as e:
                if e == 401:
                    admin_page_found.append('http://'+url_request)
                else:
                    ++admin_page_not_found
            except urllib3.exceptions.RequestError:
                pass
            else:
                admin_page_found.append('http://' + url_request)

        print(G+'[!] Admin Pages Found: '+str(len(admin_page_found)))

        for page in admin_page_found:
            print(lB+'\n[+] '+ page)