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


Python error.ConnectError方法代码示例

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


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

示例1: request

# 需要导入模块: from twisted.internet import error [as 别名]
# 或者: from twisted.internet.error import ConnectError [as 别名]
def request(self, callback, method, url, **kwargs):
        if 'data' in kwargs and not isinstance(kwargs['data'], bytes):
            # python2/3 compatibility
            data = kwargs.pop('data')
            kwargs['data'] = data.encode(encoding='utf-8') \
                if hasattr(data, 'encode') else b(data)

        try:
            response = yield self.client.request(method, url, **kwargs)
            parsed = yield self._get_resp(response)
            returnValue(callback(self.response(*parsed)))
        except ConnectError as e:
            raise ConsulException(
                '{}: {}'.format(e.__class__.__name__, e.message))
        except ResponseNeverReceived:
            # this exception is raised if the connection to the server is lost
            # when yielding a response, this could be due to network issues or
            # server restarts
            raise ConsulException(
                'Server connection lost: {} {}'.format(method.upper(), url))
        except RequestTransmissionFailed:
            # this exception is expected if the reactor is stopped mid request
            raise ConsulException(
                'Request incomplete: {} {}'.format(method.upper(), url)) 
开发者ID:poppyred,项目名称:python-consul2,代码行数:26,代码来源:twisted.py

示例2: logOn

# 需要导入模块: from twisted.internet import error [as 别名]
# 或者: from twisted.internet.error import ConnectError [as 别名]
def logOn(self, chatui):
        """Log on to this account.

        Takes care to not start a connection if a connection is
        already in progress.  You will need to implement
        L{_startLogOn} for this to work, and it would be a good idea
        to override L{_loginFailed} too.

        @returntype: Deferred L{interfaces.IClient}
        """
        if (not self._isConnecting) and (not self._isOnline):
            self._isConnecting = 1
            d = self._startLogOn(chatui)
            d.addCallback(self._cb_logOn)
            # if chatui is not None:
            # (I don't particularly like having to pass chatUI to this function,
            # but we haven't factored it out yet.)
            d.addCallback(chatui.registerAccountClient)
            d.addErrback(self._loginFailed)
            return d
        else:
            raise error.ConnectError("Connection in progress") 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:24,代码来源:basesupport.py

示例3: test_clientConnectionFailed

# 需要导入模块: from twisted.internet import error [as 别名]
# 或者: from twisted.internet.error import ConnectError [as 别名]
def test_clientConnectionFailed(self):
        """
        Calls to L{_WrappingFactory.clientConnectionLost} should errback the
        L{_WrappingFactory._onConnection} L{Deferred}
        """
        wf = endpoints._WrappingFactory(TestFactory())
        expectedFailure = Failure(error.ConnectError(string="fail"))

        wf.clientConnectionFailed(None, expectedFailure)

        errors = []

        def gotError(f):
            errors.append(f)

        wf._onConnection.addErrback(gotError)

        self.assertEqual(errors, [expectedFailure]) 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:20,代码来源:test_endpoints.py

示例4: test_endpointConnectFailure

# 需要导入模块: from twisted.internet import error [as 别名]
# 或者: from twisted.internet.error import ConnectError [as 别名]
def test_endpointConnectFailure(self):
        """
        If an endpoint tries to connect to a non-listening port it gets
        a C{ConnectError} failure.
        """
        expectedError = error.ConnectError(string="Connection Failed")

        mreactor = RaisingMemoryReactor(connectException=expectedError)

        clientFactory = object()

        ep, ignoredArgs, ignoredDest = self.createClientEndpoint(
            mreactor, clientFactory)

        d = ep.connect(clientFactory)

        receivedExceptions = []

        def checkFailure(f):
            receivedExceptions.append(f.value)

        d.addErrback(checkFailure)

        self.assertEqual(receivedExceptions, [expectedError]) 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:26,代码来源:test_endpoints.py

示例5: test_endpointConnectFailureAfterIteration

# 需要导入模块: from twisted.internet import error [as 别名]
# 或者: from twisted.internet.error import ConnectError [as 别名]
def test_endpointConnectFailureAfterIteration(self):
        """
        If a connection attempt initiated by
        L{HostnameEndpoint.connect} fails only after
        L{HostnameEndpoint} has exhausted the list of possible server
        addresses, the returned L{Deferred} will fail with
        C{ConnectError}.
        """
        expectedError = error.ConnectError(string="Connection Failed")

        mreactor = MemoryReactor()

        clientFactory = object()

        ep, ignoredArgs, ignoredDest = self.createClientEndpoint(
            mreactor, clientFactory)

        d = ep.connect(clientFactory)
        mreactor.advance(0.3)
        host, port, factory, timeout, bindAddress = mreactor.tcpClients[0]
        factory.clientConnectionFailed(mreactor.connectors[0], expectedError)
        self.assertEqual(self.failureResultOf(d).value, expectedError)
        self.assertEqual([], mreactor.getDelayedCalls()) 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:25,代码来源:test_endpoints.py

示例6: _process_error

# 需要导入模块: from twisted.internet import error [as 别名]
# 或者: from twisted.internet.error import ConnectError [as 别名]
def _process_error(self, failure):
        err = failure.value
        if isinstance(err, gcmclient.GCMAuthenticationError):
            self.log.error("GCM Authentication Error: %s" % err)
            raise RouterException("Server error", status_code=500,
                                  errno=901)
        if isinstance(err, TimeoutError):
            self.log.warn("GCM Timeout: %s" % err)
            self.metrics.increment("notification.bridge.error",
                                   tags=make_tags(
                                       self._base_tags,
                                       reason="timeout"))
            raise RouterException("Server error", status_code=502,
                                  errno=903,
                                  log_exception=False)
        if isinstance(err, ConnectError):
            self.log.warn("GCM Unavailable: %s" % err)
            self.metrics.increment("notification.bridge.error",
                                   tags=make_tags(
                                       self._base_tags,
                                       reason="connection_unavailable"))
            raise RouterException("Server error", status_code=502,
                                  errno=902,
                                  log_exception=False)
        return failure 
开发者ID:mozilla-services,项目名称:autopush,代码行数:27,代码来源:gcm.py

示例7: test_connect_fails

# 需要导入模块: from twisted.internet import error [as 别名]
# 或者: from twisted.internet.error import ConnectError [as 别名]
def test_connect_fails(self):
        reactor = object()
        connect_d = defer.Deferred()
        stderr = io.StringIO()
        with mock.patch(
                "wormhole.tor_manager.txtorcon.connect",
                side_effect=connect_d) as connect:
            with mock.patch(
                    "wormhole.tor_manager.clientFromString",
                    side_effect=["foo"]) as sfs:
                d = get_tor(reactor, stderr=stderr)
        self.assertEqual(sfs.mock_calls, [])
        self.assertNoResult(d)
        self.assertEqual(connect.mock_calls, [mock.call(reactor)])

        connect_d.errback(ConnectError())
        tor = self.successResultOf(d)
        self.assertIsInstance(tor, SocksOnlyTor)
        self.assert_(ITorManager.providedBy(tor))
        self.assertEqual(tor._reactor, reactor)
        self.assertEqual(
            stderr.getvalue(),
            " unable to find default Tor control port, using SOCKS\n") 
开发者ID:warner,项目名称:magic-wormhole,代码行数:25,代码来源:test_tor_manager.py

示例8: test_connect_custom_control_port_fails

# 需要导入模块: from twisted.internet import error [as 别名]
# 或者: from twisted.internet.error import ConnectError [as 别名]
def test_connect_custom_control_port_fails(self):
        reactor = object()
        tcp = "port"
        ep = object()
        connect_d = defer.Deferred()
        stderr = io.StringIO()
        with mock.patch(
                "wormhole.tor_manager.txtorcon.connect",
                side_effect=connect_d) as connect:
            with mock.patch(
                    "wormhole.tor_manager.clientFromString",
                    side_effect=[ep]) as sfs:
                d = get_tor(reactor, tor_control_port=tcp, stderr=stderr)
        self.assertEqual(sfs.mock_calls, [mock.call(reactor, tcp)])
        self.assertNoResult(d)
        self.assertEqual(connect.mock_calls, [mock.call(reactor, ep)])

        connect_d.errback(ConnectError())
        self.failureResultOf(d, ConnectError)
        self.assertEqual(stderr.getvalue(), "") 
开发者ID:warner,项目名称:magic-wormhole,代码行数:22,代码来源:test_tor_manager.py

示例9: test_clientConnectionFailed

# 需要导入模块: from twisted.internet import error [as 别名]
# 或者: from twisted.internet.error import ConnectError [as 别名]
def test_clientConnectionFailed(self):
        """
        Calls to L{_WrappingFactory.clientConnectionLost} should errback the
        L{_WrappingFactory._onConnection} L{Deferred}
        """
        wf = endpoints._WrappingFactory(TestFactory(), None)
        expectedFailure = Failure(error.ConnectError(string="fail"))

        wf.clientConnectionFailed(
            None,
            expectedFailure)

        errors = []
        def gotError(f):
            errors.append(f)

        wf._onConnection.addErrback(gotError)

        self.assertEquals(errors, [expectedFailure]) 
开发者ID:kuri65536,项目名称:python-for-android,代码行数:21,代码来源:test_endpoints.py

示例10: get_grid_status

# 需要导入模块: from twisted.internet import error [as 别名]
# 或者: from twisted.internet.error import ConnectError [as 别名]
def get_grid_status(self):
        if not self.nodeurl:
            return None
        try:
            resp = yield treq.get(self.nodeurl + "?t=json")
        except ConnectError:
            return None
        if resp.code == 200:
            content = yield treq.content(resp)
            content = json.loads(content.decode("utf-8"))
            servers_connected = 0
            servers_known = 0
            available_space = 0
            if "servers" in content:
                servers = content["servers"]
                servers_known = len(servers)
                for server in servers:
                    if server["connection_status"].startswith("Connected"):
                        servers_connected += 1
                        if server["available_space"]:
                            available_space += server["available_space"]
            return servers_connected, servers_known, available_space
        return None 
开发者ID:gridsync,项目名称:gridsync,代码行数:25,代码来源:tahoe.py

示例11: _make_connections

# 需要导入模块: from twisted.internet import error [as 别名]
# 或者: from twisted.internet.error import ConnectError [as 别名]
def _make_connections(self, eventloop, addresses):
        """Connect to `eventloop` using all `addresses`."""
        for address in addresses:
            try:
                connection = yield self._make_connection(eventloop, address)
            except ConnectError as error:
                host, port = address
                log.msg(
                    "Event-loop %s (%s:%d): %s"
                    % (eventloop, host, port, error)
                )
            except Exception:
                host, port = address
                log.err(
                    None,
                    (
                        "Failure with event-loop %s (%s:%d)"
                        % (eventloop, host, port)
                    ),
                )
            else:
                self.try_connections[eventloop] = connection
                break 
开发者ID:maas,项目名称:maas,代码行数:25,代码来源:clusterservice.py

示例12: make_restconf_connection

# 需要导入模块: from twisted.internet import error [as 别名]
# 或者: from twisted.internet.error import ConnectError [as 别名]
def make_restconf_connection(self, get_timeout=None):
        client = self._rest_client

        if client is None:
            client = AdtranRestClient(self.ip_address,
                                      self.rest_port,
                                      self.rest_username,
                                      self.rest_password,
                                      self.timeout)

        timeout = get_timeout or self.timeout

        try:
            request = client.request('GET', self.HELLO_URI, name='hello', timeout=timeout)
            results = yield request
            if isinstance(results, dict) and 'module-info' in results:
                self._rest_client = client
                returnValue(results)
            else:
                from twisted.internet.error import ConnectError
                self._rest_client = None
                raise ConnectError(string='Results received but unexpected data type or contents')
        except Exception:
            self._rest_client = None
            raise 
开发者ID:opencord,项目名称:voltha,代码行数:27,代码来源:adtran_device_handler.py

示例13: handleCmdConnectFailure

# 需要导入模块: from twisted.internet import error [as 别名]
# 或者: from twisted.internet.error import ConnectError [as 别名]
def handleCmdConnectFailure(self, failure):
        log.error("CMD CONNECT: %s" % failure.getErrorMessage())

        # Map common twisted errors to SOCKS error codes
        if failure.type == error.NoRouteError:
            self.sendReply(SOCKSv5Reply.NetworkUnreachable)
        elif failure.type == error.ConnectionRefusedError:
            self.sendReply(SOCKSv5Reply.ConnectionRefused)
        elif failure.type == error.TCPTimedOutError or failure.type == error.TimeoutError:
            self.sendReply(SOCKSv5Reply.TTLExpired)
        elif failure.type == error.UnsupportedAddressFamily:
            self.sendReply(SOCKSv5Reply.AddressTypeNotSupported)
        elif failure.type == error.ConnectError:
            # Twisted doesn't have a exception defined for EHOSTUNREACH,
            # so the failure is a ConnectError.  Try to catch this case
            # and send a better reply, but fall back to a GeneralFailure.
            reply = SOCKSv5Reply.GeneralFailure
            try:
                import errno
                if hasattr(errno, "EHOSTUNREACH"):
                    if failure.value.osError == errno.EHOSTUNREACH:
                        reply = SOCKSv5Reply.HostUnreachable
                if hasattr(errno, "WSAEHOSTUNREACH"):
                    if failure.value.osError == errno.WSAEHOSTUNREACH:
                        reply = SOCKSv5Reply.HostUnreachable
            except Exception:
                pass
            self.sendReply(reply)
        else:
            self.sendReply(SOCKSv5Reply.GeneralFailure)

        failure.trap(error.NoRouteError, error.ConnectionRefusedError,
                     error.TCPTimedOutError, error.TimeoutError,
                     error.UnsupportedAddressFamily, error.ConnectError) 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:36,代码来源:socks5.py

示例14: connectionLost

# 需要导入模块: from twisted.internet import error [as 别名]
# 或者: from twisted.internet.error import ConnectError [as 别名]
def connectionLost(self, reason):
        if self.instance:
            self.instance.connectionLost(reason)
        else:
            # Some HTTP proxies (Eg: polipo) are rude and opt to close the
            # connection instead of sending a status code indicating failure.
            self.onConnectionError(ConnectError("Proxy connection closed during setup")) 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:9,代码来源:http.py

示例15: handleStatus

# 需要导入模块: from twisted.internet import error [as 别名]
# 或者: from twisted.internet.error import ConnectError [as 别名]
def handleStatus(self, version, status, message):
        if status != "200":
            self.onConnectionError(ConnectError("Proxy returned status: %s" % status)) 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:5,代码来源:http.py


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