本文整理汇总了Python中twisted.python.failure.trap函数的典型用法代码示例。如果您正苦于以下问题:Python trap函数的具体用法?Python trap怎么用?Python trap使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了trap函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: error_callback
def error_callback(self,failure,payload):
try:
failure.trap(CommandException)
# the next line will only run if failure is a CommandException
self.args = payload
except twisted.python.failure.Failure:
pass
示例2: _trap_nosuchcodeimportjob
def _trap_nosuchcodeimportjob(self, failure):
failure.trap(xmlrpc.Fault)
if failure.value.faultCode == NoSuchCodeImportJob.error_code:
self._call_finish_job = False
raise ExitQuietly
else:
raise failure.value
示例3: _sessionClosed
def _sessionClosed(self, maybeFailure, sessionID):
del self.sessions[sessionID]
if isinstance(maybeFailure, failure.Failure):
failure.trap(error.ConnectionDone,
error.ConnectionLost,
SessionTimeout)
else:
return maybeFailure
示例4: relookup
def relookup(failure):
failure.trap(error.DNSNameError)
if type == dns.PTR:
ip = self._reverse_ip(name)
d = threads.deferToThread(self._ec2.get_all_instances, filters={self.reverse_filter: ip})
d.addCallback(self.create_message, name, self.forward_filter, record=dns.PTR)
elif type == dns.A:
d = threads.deferToThread(self._ec2.get_all_instances, filters={self.forward_filter: str(name)})
d.addCallback(self.create_message, name, self.reverse_filter, record=dns.A)
else:
raise ValueError, "Record constant '%s' is not supported" % (type)
return d
示例5: err_overload
def err_overload(self, failure, message_type):
"""Handle database overloads
Pause producing to cease incoming notifications while we wait a random
interval up to 8 seconds before closing down the connection. Most
clients wait up to 10 seconds for a command, but this is not a
guarantee, so rather than never reply, we still shut the connection
down.
"""
failure.trap(ProvisionedThroughputExceededException)
self.transport.pauseProducing()
d = self.deferToLater(random.randrange(4, 9), self.err_finish_overload, message_type)
d.addErrback(self.trap_cancel)
示例6: _retry_local_port
def _retry_local_port(self, failure):
"""
Handles :api:`twisted.internet.error.CannotListenError` by
trying again on another port. After 10 failures, we give up
and propogate the error.
"""
failure.trap(error.CannotListenError)
self.retries += 1
if self.retries > 10:
return failure
self.listen_port = self.port_generator()
## we do want to overwrite the whole list, not append
self.hiddenservice.ports = ['%d 127.0.0.1:%d' % (self.public_port, self.listen_port)]
d = self.config.save()
d.addCallback(self._create_listener).addErrback(self._retry_local_port)
return d
示例7: _label_helper
def _label_helper(self, failure, debug=False):
"""
Errback, который ловит L{SkipToProcess}, чтобы обеcпечить остановку
на нужном label после skip to.
@param debug: включить отладочный режим?
@type debug: C{bool}
"""
failure.trap(SkipToProcess)
if failure.value.label != self.label:
if debug:
failure.value.pack.debug("Labels for skip don't match %d != %d" % (failure.value.label, self.label))
return failure
if debug:
failure.value.pack.debug("Stopped skip to at label %d" % self.label)
return failure.value.pack
示例8: _ebRoundRobinBackoff
def _ebRoundRobinBackoff(self, failure, fakeProto):
failure.trap(defer.TimeoutError)
# Assert that each server is tried with a particular timeout
# before the timeout is increased and the attempts are repeated.
for t in (1, 3, 11, 45):
tries = fakeProto.queries[:len(self.testServers)]
del fakeProto.queries[:len(self.testServers)]
tries.sort()
expected = list(self.testServers)
expected.sort()
for ((addr, query, timeout, id), expectedAddr) in zip(tries, expected):
self.assertEquals(addr, (expectedAddr, 53))
self.assertEquals(timeout, t)
self.failIf(fakeProto.queries)
示例9: loginFailed
def loginFailed(failure):
def gotRoot(root):
# an idempotent method, should return a network failure if
# the remote side disconnects as it should
return root.callRemote("getKeycardClasses")
def gotError(failure):
self.assertAdditionalFDsOpen(1, "feedSent (socket)")
self.info("success")
def gotKeycardClasses(classes):
raise AssertionError("should not get here")
self.info("loginFailed: %s", log.getFailureMessage(failure))
failure.trap(errors.NotAuthenticatedError)
d = factory.getRootObject() # should fire immediately
d.addCallback(gotRoot)
d.addCallbacks(gotKeycardClasses, gotError)
return d
示例10: test_invalid_domain
def test_invalid_domain(self):
"""Tests sending to a domain we don't have mappings for."""
rcpt = smtp.User("[email protected]", None, object(), self.sender)
ret = self._sendMessage(rcpt, False)
ret.addCallbacks(
self.fail,
lambda failure: failure.trap(smtp.SMTPBadRcpt)
)
ret.addCallback(self._checkLogs, [("user", "invaliddomain.com",
logging.ERROR, str(self.sender), str(rcpt.dest), 0)])
return ret
示例11: test_invalid_address
def test_invalid_address(self):
"""Tests sending to an invalid address."""
rcpt = smtp.User("[email protected]", None, object(), self.sender)
ret = self._sendMessage(rcpt, False)
ret.addCallbacks(
self.fail,
lambda failure: failure.trap(smtp.SMTPBadRcpt)
)
ret.addCallback(self._checkLogs, [("doesnotexist", "smtp2web.com",
logging.ERROR, str(self.sender), str(rcpt.dest), 0)])
return ret
示例12: test_send_fail
def test_send_fail(self):
"""Tests sending with a handler that raises an exception."""
rcpt = smtp.User("[email protected]", None, object(), self.sender)
ret = self._sendMessage(rcpt)
ret.addCallbacks(
self.fail,
lambda failure: failure.trap(smtp2web.MessageSubmissionError)
)
handler = self.settings.usermap['smtp2web.com'].findHandler("fail")
ret.addCallback(lambda x: self.failUnlessEqual(handler.invocations,
[(str(self.sender), str(rcpt.dest), self.test_message)]))
ret.addCallback(self._checkLogs, [("fail", "smtp2web.com", logging.ERROR,
str(self.sender), str(rcpt.dest), len(self.test_message))])
return ret
示例13: __checkJobStepResults
def __checkJobStepResults(self, failure, status):
"Check that given self.js.status is set to correct value after certain JobStep operation"
twisted_logger.writeLog(self.logPrefix, None, "Checking test results...")
if failure is not None:
error = failure.getErrorMessage()
failure.trap(RuntimeError)
print "ERROR: %s" % error
else:
error = None
query = "select status, text_input, error, start_time, end_time from scs.job_step " \
"where job_id = %d and step_id = %d" % (self.js.jobID, self.js.stepID)
res = synchdb.query(query)
db_status, text_input, db_error, start_time, end_time = res[0]
self.assertEquals(str(self.js.input), text_input, "<scs.job_step> text_input ('%s') not equals to expected input ('%s')" % (text_input, str(self.js.input)))
self.assertEquals(error, db_error, "<scs.job_step> error ('%s') not equals to expected error ('%s')" % (db_error, error))
self.assertEquals(status, db_status, "<scs.job_step> status ('%s') not equals to expected status ('%s')" % (db_status, status))
self.assertEquals(self.js.status, status, "<js.status> ('%s') not equals to expected status ('%s')" % (self.js.status, status))
if self.js.status != 'RUNNING':
self.assertNotEquals(end_time, None)
twisted_logger.writeLog(self.logPrefix, None, "Test succeeded!")
示例14: __call__
def __call__(self, failure):
r = failure.trap(weberror.Error,error.ConnectionRefusedError)
if r == error.ConnectionRefusedError:
status = int(http.INTERNAL_SERVER_ERROR)
else:
status = int(failure.value.status)
if status == http.NOT_FOUND:
if self.seen404:
return failure
else:
self.seen404 = True
elif status not in self.okErrs:
return failure
示例15: error
def error (failure, try_again = 0):
if try_again is not 0:
failure.trap(BufferedCommandFailed)
d = task.deferLater(reactor, 0.2, fn, id, command)
d.addCallbacks(next, error, errbackKeywords = { "try_again": try_again - 1 })
return d