本文整理匯總了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))
示例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")
示例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])
示例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])
示例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())
示例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
示例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")
示例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(), "")
示例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])
示例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
示例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
示例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
示例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)
示例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"))
示例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))