当前位置: 首页>>代码示例>>Python>>正文


Python exceptions.NewConnectionError方法代码示例

本文整理汇总了Python中urllib3.exceptions.NewConnectionError方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.NewConnectionError方法的具体用法?Python exceptions.NewConnectionError怎么用?Python exceptions.NewConnectionError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在urllib3.exceptions的用法示例。


在下文中一共展示了exceptions.NewConnectionError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: connect

# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import NewConnectionError [as 别名]
def connect(self):
        logger.debug('[MyHTTPConnection] connect %s:%i', self.host, self.port)
        try:
            self._tor_stream = self._circuit.create_stream((self.host, self.port))
            logger.debug('[MyHTTPConnection] tor_stream create_socket')
            self.sock = self._tor_stream.create_socket()
            if self._tunnel_host:
                self._tunnel()
        except TimeoutError:
            logger.error('TimeoutError')
            raise ConnectTimeoutError(
                self, 'Connection to %s timed out. (connect timeout=%s)' % (self.host, self.timeout)
            )
        except Exception as e:
            logger.error('NewConnectionError')
            raise NewConnectionError(self, 'Failed to establish a new connection: %s' % e) 
开发者ID:torpyorg,项目名称:torpy,代码行数:18,代码来源:adapter.py

示例2: get_info

# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import NewConnectionError [as 别名]
def get_info(self):
        if not self.is_checked:
            try:
                r = requests.get(str(self), timeout=(10, 3))
                if r.status_code == 200:
                    self.server = r.headers['Server']
                elif r.status_code >= 400:
                    raise TargetNotExistException(self.url)
            except requests.exceptions.ReadTimeout as rt:
                logger.exception(rt)

            try:
                url = re.compile(r"https?://(www\.)?")
                self.url_c = url.sub('', self.url).strip().strip('/')
                self.ip = socket.gethostbyname(self.url_c)
            except socket.gaierror as err:
                logger.exception(err)
            except NewConnectionError:
                raise TargetNotExistException(self.url)

            self.is_checked = True 
开发者ID:maxkrivich,项目名称:SlowLoris,代码行数:23,代码来源:targetinfo.py

示例3: get_resource

# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import NewConnectionError [as 别名]
def get_resource(self, resource, namespace="all"):
        ret, resources = None, list()
        try:
            ret, namespaced_resource = self._call_api_client(resource)
        except ApiException as ae:
            self.logger.warning("resource autocomplete disabled, encountered "
                                "ApiException", exc_info=1)
        except (NewConnectionError, MaxRetryError, ConnectTimeoutError):
            self.logger.warning("unable to connect to k8 cluster", exc_info=1)
        if ret:
            for i in ret.items:
                if namespace == "all" or not namespaced_resource:
                    resources.append((i.metadata.name, i.metadata.namespace))
                elif namespace == i.metadata.namespace:
                    resources.append((i.metadata.name, i.metadata.namespace))
        return resources 
开发者ID:cloudnativelabs,项目名称:kube-shell,代码行数:18,代码来源:client.py

示例4: get

# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import NewConnectionError [as 别名]
def get(self, url: str, params: Dict[str, str] = None) -> Response:
        """Perform HTTP GET request.

        :param url: the request url
        :param params: the request params
        :return: the response from server
        :raise: :exc:`ConnectionError <stellar_sdk.exceptions.ConnectionError>`
        """
        try:
            resp = requests.get(url=url, params=params, headers=HEADERS)
        except (RequestException, NewConnectionError) as err:
            raise ConnectionError(err)
        return Response(
            status_code=resp.status_code,
            text=resp.text,
            headers=dict(resp.headers),
            url=resp.url,
        ) 
开发者ID:StellarCN,项目名称:py-stellar-base,代码行数:20,代码来源:simple_requests_client.py

示例5: post

# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import NewConnectionError [as 别名]
def post(self, url: str, data: Dict[str, str]) -> Response:
        """Perform HTTP POST request.

        :param url: the request url
        :param data: the data send to server
        :return: the response from server
        :raise: :exc:`ConnectionError <stellar_sdk.exceptions.ConnectionError>`
        """
        try:
            resp = requests.post(url=url, data=data, headers=HEADERS)
        except (RequestException, NewConnectionError) as err:
            raise ConnectionError(err)
        return Response(
            status_code=resp.status_code,
            text=resp.text,
            headers=dict(resp.headers),
            url=resp.url,
        ) 
开发者ID:StellarCN,项目名称:py-stellar-base,代码行数:20,代码来源:simple_requests_client.py

示例6: get

# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import NewConnectionError [as 别名]
def get(self, url: str, params: Dict[str, str] = None) -> Response:
        """Perform HTTP GET request.

        :param url: the request url
        :param params: the request params
        :return: the response from server
        :raise: :exc:`ConnectionError <stellar_sdk.exceptions.ConnectionError>`
        """
        try:
            resp = self._session.get(url, params=params, timeout=self.request_timeout)
        except (RequestException, NewConnectionError) as err:
            raise ConnectionError(err)
        return Response(
            status_code=resp.status_code,
            text=resp.text,
            headers=dict(resp.headers),
            url=resp.url,
        ) 
开发者ID:StellarCN,项目名称:py-stellar-base,代码行数:20,代码来源:requests_client.py

示例7: post

# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import NewConnectionError [as 别名]
def post(self, url: str, data: Dict[str, str] = None) -> Response:
        """Perform HTTP POST request.

        :param url: the request url
        :param data: the data send to server
        :return: the response from server
        :raise: :exc:`ConnectionError <stellar_sdk.exceptions.ConnectionError>`
        """
        try:
            resp = self._session.post(url, data=data, timeout=self.post_timeout)
        except (RequestException, NewConnectionError) as err:
            raise ConnectionError(err)
        return Response(
            status_code=resp.status_code,
            text=resp.text,
            headers=dict(resp.headers),
            url=resp.url,
        ) 
开发者ID:StellarCN,项目名称:py-stellar-base,代码行数:20,代码来源:requests_client.py

示例8: test_retries_on_transport

# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import NewConnectionError [as 别名]
def test_retries_on_transport(execute_mock):
    """Testing retries on the transport level

    This forces us to override low-level APIs because the retry mechanism on the urllib3
    (which uses requests) is pretty low-level itself.
    """
    expected_retries = 3
    execute_mock.side_effect = NewConnectionError(
        "Should be HTTPConnection", "Fake connection error"
    )
    transport = RequestsHTTPTransport(
        url="http://127.0.0.1:8000/graphql", retries=expected_retries,
    )
    client = Client(transport=transport)

    query = gql(
        """
        {
          myFavoriteFilm: film(id:"RmlsbToz") {
            id
            title
            episodeId
          }
        }
        """
    )
    with client as session:  # We're using the client as context manager
        with pytest.raises(Exception):
            session.execute(query)

    # This might look strange compared to the previous test, but making 3 retries
    # means you're actually doing 4 calls.
    assert execute_mock.call_count == expected_retries + 1 
开发者ID:graphql-python,项目名称:gql,代码行数:35,代码来源:test_client.py

示例9: set_up_index

# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import NewConnectionError [as 别名]
def set_up_index(self):
        try:
            try:
                try:
                    index_exists = self.__es_conn__.indices.exists(index=__index_name__)
                    if not index_exists:
                        self.create_index()
                    else:
                        res = self.__es_conn__.indices.get_mapping(index=__index_name__)
                        try:
                            current_version = res[__index_name__]['mappings']['_meta']['version']
                            if current_version < __index_version__:
                                self.update_index(current_version)
                            elif current_version is None:
                                logger.error("Old Index Mapping. Manually reindex the index to persist your data.")
                                print("\n -- Old Index Mapping. Manually reindex the index to persist your data.--\n")
                                sys.exit(1)
                        except KeyError:
                            logger.error("Old Index Mapping. Manually reindex the index to persist your data.")
                            print("\n -- Old Index Mapping. Manually reindex the index to persist your data.--\n")
                            sys.exit(1)

                except ESConnectionError as e:
                    logger.error("Elasticsearch is not installed or its service is not running. {0}".format(e))
                    print("\n -- Elasticsearch is not installed or its service is not running.--\n", e)
                    sys.exit(1)
            except NewConnectionError:
                pass
        except ConnectionRefusedError:
            pass 
开发者ID:5hirish,项目名称:adam_qas,代码行数:32,代码来源:es_connect.py

示例10: _new_conn

# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import NewConnectionError [as 别名]
def _new_conn(self):
        logger.debug('[MyHTTPSConnection] new conn %s:%i', self.host, self.port)
        try:
            self._tor_stream = self._circuit.create_stream((self.host, self.port))
            logger.debug('[MyHTTPSConnection] tor_stream create_socket')
            return self._tor_stream.create_socket()
        except TimeoutError:
            logger.error('TimeoutError')
            raise ConnectTimeoutError(
                self, 'Connection to %s timed out. (connect timeout=%s)' % (self.host, self.timeout)
            )
        except Exception as e:
            logger.error('NewConnectionError')
            raise NewConnectionError(self, 'Failed to establish a new connection: %s' % e) 
开发者ID:torpyorg,项目名称:torpy,代码行数:16,代码来源:adapter.py

示例11: run

# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import NewConnectionError [as 别名]
def run(count=0):
    global bot
    try:
        bot = Bot(multi_logs=True, selenium_local_session=False,
                  proxy_address_port=get_proxy(os.environ.get('INSTA_USER')), disable_image_load=True)
        selenium_url = "http://%s:%d/wd/hub" % (os.environ.get('SELENIUM', 'selenium'), 4444)
        bot.set_selenium_remote_session(logger=logging.getLogger(), selenium_url=selenium_url, selenium_driver=selenium_driver(selenium_url))
        bot.login()
        bot.set_settings()
        bot.act()
    except (NewConnectionError, WebDriverException) as exc:
        bot.logger.warning("Exception in run: %s; try again: count=%s" % (exc, count))
        if count > 3:
            print("Exception in run(): %s \n %s" % (exc, traceback.format_exc()))
            report_exception(exc)
        else:
            run(count=count + 1)

    except (ProtocolError, MaxRetryError) as exc:
        bot.logger.error("Abort because of %s; \n%s" % (exc, traceback.format_exc()))
        return

    except Exception as exc:
        print("Exception in run(): %s \n %s" % (exc, traceback.format_exc()))
        report_exception(exc)
    finally:
        print("END")
        bot.end() 
开发者ID:Instagram-Tools,项目名称:bot,代码行数:30,代码来源:docker_quickstart.py

示例12: run

# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import NewConnectionError [as 别名]
def run(count=0):
    global bot
    try:
        bot = Bot(multi_logs=True, selenium_local_session=False,
                  proxy_address_port=get_proxy(os.environ.get('INSTA_USER')), disable_image_load=False)
        selenium_url = "http://%s:%d/wd/hub" % (os.environ.get('SELENIUM', 'selenium'), 4444)
        bot.set_selenium_remote_session(logger=logging.getLogger(), selenium_url=selenium_url, selenium_driver=selenium_driver(selenium_url))
        bot.try_first_login()
    except (NewConnectionError, NewConnectionError) as exc:
        bot.logger.warning("Exception in run: %s; try again: count=%s" % (exc, count))
        if count > 3:
            print("Exception in run(): %s \n %s" % (exc, traceback.format_exc()))
            report_exception(exc)
        else:
            run(count=count + 1)

    except (ProtocolError, MaxRetryError) as exc:
        bot.logger.error("Abort because of %s; \n%s" % (exc, traceback.format_exc()))
        return

    except Exception as exc:
        print("Exception in run(): %s \n %s" % (exc, traceback.format_exc()))
        report_exception(exc)
    finally:
        print("END")
        bot.end() 
开发者ID:Instagram-Tools,项目名称:bot,代码行数:28,代码来源:docker_tryLogin.py

示例13: send

# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import NewConnectionError [as 别名]
def send(self, method="GET", *args, **kwargs):
        """
        Send a GET/POST/HEAD request using the object's proxies and headers
        :param method: Method to send request in. GET/POST/HEAD
        """
        proxies = self._get_request_proxies()

        try:
            if method.upper() in self.allowed_methods:
                kwargs['timeout'] = kwargs['timeout'] if 'timeout' in kwargs else 5
                return request(method, proxies=proxies, headers=self.headers, cookies=self.cookies, *args, **kwargs)
            else:
                raise RequestHandlerException("Unsupported method: {}".format(method))
        except ProxyError:
            # TODO: Apply fail over for bad proxies or drop them
            raise RequestHandlerException("Error connecting to proxy")
        except (ConnectTimeout, ReadTimeout):
            raise RequestHandlerException("Connection with server timed out")
        except NewConnectionError:
            raise RequestHandlerException("Address cannot be resolved")
            # New connection error == Can't resolve address
        except ConnectionError:
            # TODO: Increase delay
            raise RequestHandlerException("Error connecting to host")
        except TooManyRedirects:
            raise RequestHandlerException("Infinite redirects detected - too many redirects error")
        except UnicodeDecodeError:
            # Following issue #19, apparently some sites do not use utf-8 in their uris :<>
            pass 
开发者ID:evyatarmeged,项目名称:Raccoon,代码行数:31,代码来源:request_handler.py

示例14: send

# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import NewConnectionError [as 别名]
def send(self, request):
        try:
            proxy_url = self._proxy_config.proxy_url_for(request.url)
            manager = self._get_connection_manager(request.url, proxy_url)
            conn = manager.connection_from_url(request.url)
            self._setup_ssl_cert(conn, request.url, self._verify)

            request_target = self._get_request_target(request.url, proxy_url)
            urllib_response = conn.urlopen(
                method=request.method,
                url=request_target,
                body=request.body,
                headers=request.headers,
                retries=False,
                assert_same_host=False,
                preload_content=False,
                decode_content=False,
            )

            http_response = botocore.awsrequest.AWSResponse(
                request.url,
                urllib_response.status,
                urllib_response.headers,
                urllib_response,
            )

            if not request.stream_output:
                # Cause the raw stream to be exhausted immediately. We do it
                # this way instead of using preload_content because
                # preload_content will never buffer chunked responses
                http_response.content

            return http_response
        except URLLib3SSLError as e:
            raise SSLError(endpoint_url=request.url, error=e)
        except (NewConnectionError, socket.gaierror) as e:
            raise EndpointConnectionError(endpoint_url=request.url, error=e)
        except ProxyError as e:
            raise ProxyConnectionError(proxy_url=proxy_url, error=e)
        except URLLib3ConnectTimeoutError as e:
            raise ConnectTimeoutError(endpoint_url=request.url, error=e)
        except URLLib3ReadTimeoutError as e:
            raise ReadTimeoutError(endpoint_url=request.url, error=e)
        except ProtocolError as e:
            raise ConnectionClosedError(
                error=e,
                request=request,
                endpoint_url=request.url
            )
        except Exception as e:
            message = 'Exception received when sending urllib3 HTTP request'
            logger.debug(message, exc_info=True)
            raise HTTPClientError(error=e) 
开发者ID:QData,项目名称:deepWordBug,代码行数:55,代码来源:httpsession.py

示例15: send

# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import NewConnectionError [as 别名]
def send(self, request):
        try:
            proxy_url = self._proxy_config.proxy_url_for(request.url)
            manager = self._get_connection_manager(request.url, proxy_url)
            conn = manager.connection_from_url(request.url)
            self._setup_ssl_cert(conn, request.url, self._verify)

            request_target = self._get_request_target(request.url, proxy_url)
            urllib_response = conn.urlopen(
                method=request.method,
                url=request_target,
                body=request.body,
                headers=request.headers,
                retries=False,
                assert_same_host=False,
                preload_content=False,
                decode_content=False,
                chunked=self._chunked(request.headers),
            )

            http_response = botocore.awsrequest.AWSResponse(
                request.url,
                urllib_response.status,
                urllib_response.headers,
                urllib_response,
            )

            if not request.stream_output:
                # Cause the raw stream to be exhausted immediately. We do it
                # this way instead of using preload_content because
                # preload_content will never buffer chunked responses
                http_response.content

            return http_response
        except URLLib3SSLError as e:
            raise SSLError(endpoint_url=request.url, error=e)
        except (NewConnectionError, socket.gaierror) as e:
            raise EndpointConnectionError(endpoint_url=request.url, error=e)
        except ProxyError as e:
            raise ProxyConnectionError(proxy_url=proxy_url, error=e)
        except URLLib3ConnectTimeoutError as e:
            raise ConnectTimeoutError(endpoint_url=request.url, error=e)
        except URLLib3ReadTimeoutError as e:
            raise ReadTimeoutError(endpoint_url=request.url, error=e)
        except ProtocolError as e:
            raise ConnectionClosedError(
                error=e,
                request=request,
                endpoint_url=request.url
            )
        except Exception as e:
            message = 'Exception received when sending urllib3 HTTP request'
            logger.debug(message, exc_info=True)
            raise HTTPClientError(error=e) 
开发者ID:gkrizek,项目名称:bash-lambda-layer,代码行数:56,代码来源:httpsession.py


注:本文中的urllib3.exceptions.NewConnectionError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。