本文整理汇总了Python中twisted.internet.defer.Deferred.addErrback方法的典型用法代码示例。如果您正苦于以下问题:Python Deferred.addErrback方法的具体用法?Python Deferred.addErrback怎么用?Python Deferred.addErrback使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twisted.internet.defer.Deferred
的用法示例。
在下文中一共展示了Deferred.addErrback方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: stopRemoteControlSession
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addErrback [as 别名]
def stopRemoteControlSession(self, authToken, sourceLogonId, targetLogonId):
logger.debug("stopRemoteControlSession(auth=%s, sessionId=%s targetSessionId=%s)" % (authToken, sourceLogonId, targetLogonId))
session = self.server.retrieveSession(sourceLogonId)
if not session:
logger.error("source session %s not present here" % sourceLogonId)
return False
targetSession = self.server.retrieveSession(targetLogonId)
if not targetSession:
logger.error("target session %s not present here" % targetLogonId)
return False
icpFactory = self.server.icpFactory
req = FdsApiStopRemoteControlRequest()
req.connectionId = session.connectionId
d = Deferred()
def onError(err):
logger.error('an error occured')
return ttypes.TException('Internal error in server')
def onSuccess(response):
logger.debug('response=%s' % response)
return response.success
d.addErrback(onError)
d.addCallback(onSuccess)
icpFactory.doQuery(FdsApiStopRemoteControl, req, Thrift2IcpHandler(self, d, FdsApiStopRemoteControlResponse))
return d
示例2: execute_config
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addErrback [as 别名]
def execute_config(self, log, transaction_id, scaling_group, launch_config):
"""
see :meth:`ISupervisor.execute_config`
"""
job_id = generate_job_id(scaling_group.uuid)
completion_d = Deferred()
log = log.bind(job_id=job_id,
worker=launch_config['type'],
tenant_id=scaling_group.tenant_id)
assert launch_config['type'] == 'launch_server'
undo = InMemoryUndoStack(self.coiterate)
def when_fails(result):
log.msg("Encountered an error, rewinding {worker!r} job undo stack.",
exc=result.value)
ud = undo.rewind()
ud.addCallback(lambda _: result)
return ud
completion_d.addErrback(when_fails)
log.msg("Authenticating for tenant")
d = self.auth_function(scaling_group.tenant_id, log=log)
def when_authenticated((auth_token, service_catalog)):
log.msg("Executing launch config.")
return launch_server_v1.launch_server(
log,
self.region,
scaling_group,
service_catalog,
auth_token,
launch_config['args'], undo)
d.addCallback(when_authenticated)
def when_launch_server_completed(result):
# XXX: Something should be done with this data. Currently only enough
# to pass to the controller to store in the active state is returned
server_details, lb_info = result
log.msg("Done executing launch config.",
server_id=server_details['server']['id'])
return {
'id': server_details['server']['id'],
'links': server_details['server']['links'],
'name': server_details['server']['name'],
'lb_info': lb_info
}
d.addCallback(when_launch_server_completed)
self.deferred_pool.add(d)
d.chainDeferred(completion_d)
return succeed((job_id, completion_d))
示例3: connect
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addErrback [as 别名]
def connect(self, host=None, port=None, spec=None, user=None, password=None, vhost=None,
heartbeat=None, clientClass=None):
host = host or self.host
port = port or self.port
spec = spec or self.spec
user = user or self.user
password = password or self.password
vhost = vhost or self.vhost
heartbeat = heartbeat or self.heartbeat
clientClass = clientClass or self.clientClass
delegate = TwistedDelegate()
onConn = Deferred()
p = clientClass(delegate, vhost, txamqp.spec.load(spec), heartbeat=heartbeat)
f = protocol._InstanceFactory(reactor, p, onConn)
c = reactor.connectTCP(host, port, f)
def errb(thefailure):
thefailure.trap(error.ConnectionRefusedError)
print "failed to connect to host: %s, port: %s; These tests are designed to run against a running instance" \
" of the %s AMQP broker on the given host and port. failure: %r" % (host, port, self.broker, thefailure,)
thefailure.raiseException()
onConn.addErrback(errb)
self.connectors.append(c)
client = yield onConn
yield client.authenticate(user, password)
returnValue(client)
示例4: put
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addErrback [as 别名]
def put(self, router_type="", router_token="", uaid="", chid=""):
"""HTTP PUT
Update router type/data for a UAID.
"""
self.start_time = time.time()
if not self._validate_auth(uaid):
return self._write_response(
401, 109, message="Invalid Authentication")
params = self._load_params()
self.uaid = uaid
router_data = params
if router_type not in self.ap_settings.routers or not router_data:
log.msg("Invalid parameters", **self._client_info())
return self._write_response(
400, 108, message="Invalid arguments")
router = self.ap_settings.routers[router_type]
valid, router_token = router.check_token(router_token)
if not valid:
newUrl = self._relocate(router_type, router_token, uaid, chid)
return self._write_response(
301, 0, "Location: %s" % newUrl,
headers={"Location": newUrl})
self.add_header("Content-Type", "application/json")
d = Deferred()
d.addCallback(router.register, router_data)
d.addCallback(self._save_router_data, router_type)
d.addCallback(self._success)
d.addErrback(self._router_fail_err)
d.addErrback(self._response_err)
d.callback(uaid)
示例5: put
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addErrback [as 别名]
def put(self, uaid=""):
"""HTTP PUT
Update router type/data for a UAID.
"""
self.start_time = time.time()
if not self._validate_auth(uaid):
return self._write_response(
401, 109, message="Invalid Authentication")
params = self._load_params()
self.uaid = uaid
router_type = params.get("type")
router_data = params.get("data")
if router_type not in self.ap_settings.routers or not router_data:
log.msg("Invalid parameters", **self._client_info())
return self._write_response(
400, 108, message="Invalid arguments")
self.add_header("Content-Type", "application/json")
router = self.ap_settings.routers[router_type]
d = Deferred()
d.addCallback(router.register, router_data)
d.addCallback(self._save_router_data, router_type)
d.addCallback(self._success)
d.addErrback(self._router_fail_err)
d.addErrback(self._response_err)
d.callback(uaid)
示例6: cbPostAuth
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addErrback [as 别名]
def cbPostAuth(self, response, cookie):
#print 'cbPostAuth()'
finished = Deferred()
response.deliverBody(BeginningPrinter(finished))
finished.addCallback(self.cbPostAuthSuccess, cookie)
finished.addErrback(self.cbShutdown)
return finished
示例7: _executeCommand
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addErrback [as 别名]
def _executeCommand(self, connection, protocolFactory):
"""
Given a secured SSH connection, try to execute a command in a new
channel created on it and associate the result with a protocol from the
given factory.
@param connection: See L{SSHCommandClientEndpoint.existingConnection}'s
C{connection} parameter.
@param protocolFactory: See L{SSHCommandClientEndpoint.connect}'s
C{protocolFactory} parameter.
@return: See L{SSHCommandClientEndpoint.connect}'s return value.
"""
commandConnected = Deferred()
def disconnectOnFailure(passthrough):
# Close the connection immediately in case of cancellation, since
# that implies user wants it gone immediately (e.g. a timeout):
immediate = passthrough.check(CancelledError)
self._creator.cleanupConnection(connection, immediate)
return passthrough
commandConnected.addErrback(disconnectOnFailure)
channel = _CommandChannel(
self._creator, self._command, protocolFactory, commandConnected)
connection.openChannel(channel)
return commandConnected
示例8: send_payment_request
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addErrback [as 别名]
def send_payment_request(self, readTokens, writeTokens):
"""Called by a Circuit object when it wants to actually make a payment
@param readTokens: the number of read tokens to pay for at each hop in the circuit
@type readTokens: int
@param writeTokens: the number of read tokens to pay for at each hop in the circuit
@type writeTokens: int"""
assert (readTokens + writeTokens) / Globals.CELLS_PER_PAYMENT, "tried to pay for bad number of cells"
#make sure our setup is done:
if not self.setupDone:
#have we even started?
if not self.setupStarted:
self.send_setup_message()
self.queuedReadTokens += readTokens
self.queuedWriteTokens += writeTokens
return
#dont bother trying to send payments for circuits that are already closed
if self.circ.is_done():
return
#send the payments
deferreds = []
for paymentStream in self.paymentStreams.values():
deferreds.append(paymentStream.send_payment(readTokens, writeTokens))
paymentsDoneDeferred = DeferredList(deferreds)
paymentsDoneDeferred.addErrback(self.generic_error_handler)
addTokensDeferred = Deferred()
self.inflightReadTokens += readTokens
self.inflightWriteTokens += writeTokens
#timeout in case the payment fails. We will close the circuit in this case.
event = Scheduler.schedule_once(PaymentStream.PAR_TIMEOUT, self.all_receipts_received, None, addTokensDeferred, readTokens, writeTokens, None)
paymentsDoneDeferred.addCallback(self.all_receipts_received, addTokensDeferred, readTokens, writeTokens, event)
addTokensDeferred.addCallback(self._add_tokens_callback, readTokens, writeTokens)
addTokensDeferred.addErrback(self.generic_error_handler)
示例9: hack
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addErrback [as 别名]
def hack(_, peer_id):
# Assume the parties are given a random share [r] by a
# trusted dealer.
share_r = self.random_share(field)
# 1. r = OpenTo(P_i, [r])
open_r = self.open(share_r, [peer_id])
def subtract_delta(delta, share_r):
delta = field(long(delta))
x = self.sub(share_r, delta)
return x
if peer_id == self.id:
def g(r, x):
delta = r - x
delta = self.broadcast([peer_id], self.players.keys(),
str(delta.value))
self.schedule_callback(delta, subtract_delta, share_r)
delta.addErrback(self.error_handler)
return delta
self.schedule_callback(open_r, g, number)
open_r.addErrback(self.error_handler)
return open_r
else:
d = Deferred()
def g(_, peer_id, share_r):
delta = self.broadcast([peer_id], self.players.keys())
self.schedule_callback(delta, subtract_delta, share_r)
delta.addErrback(self.error_handler)
return delta
self.schedule_callback(d, g, peer_id, share_r)
d.addErrback(self.error_handler)
d.callback(None)
return d
示例10: callRemote
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addErrback [as 别名]
def callRemote(self, method, *args, **kwargs):
"""
Call method on remote API. Method is a string and may include a package
name, such as 'admin.uptime'. Any additional arguments and keyword arguments
are passed to that method as arguments and keyword arguments.
"""
if not self.rootobj:
d = Deferred()
self.pending_calls.append((d, method, args, kwargs))
self.connect()
return d
api, method_name = method.split('.')
api = api.lower()
if self.local:
return maybeDeferred(getattr(getattr(self.app.api, api), method_name), *args, **kwargs)
else:
try:
d = self.rootobj.callRemote('api', method, *args, **kwargs)
d.addErrback(self._error_back, method, args, kwargs)
return d
except pb.DeadReferenceError:
self.rootobj = None
d = Deferred()
self.pending_calls.append((d, method, args, kwargs))
self.connect()
return d
示例11: jsonrpc_call
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addErrback [as 别名]
def jsonrpc_call(agent, server, data , bitHopper):
global i
try:
request = json.dumps({'method':'getwork', 'params':data, 'id':i}, ensure_ascii = True)
i = i +1
header = {'Authorization':["Basic " +base64.b64encode(server['user']+ ":" + server['pass'])], 'User-Agent': ['poclbm/20110709'],'Content-Type': ['application/json'] }
d = agent.request('POST', "http://" + server['mine_address'], Headers(header), StringProducer(request))
d.addErrback(bitHopper.log_dbg)
response = yield d
if response == None:
raise Exception("Response is none")
header = response.headers
#Check for long polling header
lp = bitHopper.lp
if lp.check_lp(server['pool_index']):
#bitHopper.log_msg('Inside LP check')
for k,v in header.getAllRawHeaders():
if k.lower() == 'x-long-polling':
lp.set_lp(v[0],server['pool_index'])
break
finish = Deferred()
finish.addErrback(bitHopper.log_dbg)
response.deliverBody(WorkProtocol(finish))
body = yield finish
except Exception, e:
bitHopper.log_dbg('Caught, jsonrpc_call insides')
bitHopper.log_dbg(e)
#traceback.print_exc
defer.returnValue(None)
示例12: test_upload_with_throughput_counter_and_error
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addErrback [as 别名]
def test_upload_with_throughput_counter_and_error(self):
client = FakeS3Client()
parts_generator = DummyPartsGenerator()
part_handler = ErroringPartHandler(100)
counter = PartsTransferredCounter('?')
stats = SlidingStats(self.clock.seconds(), size=100)
throughput_counter = ThroughputCounter(clock=self.clock, stats=stats)
d = Deferred()
amz_headers = {'acl': 'public-read'}
upload = MultipartUpload(client, None, parts_generator, part_handler,
counter, d, self.log)
upload.retry_strategy.clock = self.clock
upload.throughput_counter = throughput_counter
received = []
upload.on_part_generated = received.append
def eb(why):
self.flushLoggedErrors()
self.assertEquals(len(self.clock.calls), 110)
self.assertEquals(throughput_counter.read()[-1], (0, 0))
return why
upload.upload('mybucket', 'mykey', '', {}, amz_headers)
d.addErrback(eb)
return self.assertFailure(d, ValueError)
示例13: wrap_back
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addErrback [as 别名]
def wrap_back(self, msg):
'''
wrap message, to support back messages
we get some info from message headers (tid and route_back key)
and send reply with this data
'''
d = Deferred()
def _push_message(reply):
if reply == NO_REPLY:
d1 = Deferred()
d1.callback(True)
if not self.no_ack:
self.client.basic_ack(msg)
return d1
route = msg.content['headers'].get(self.rb_name)
tid = msg.content['headers'].get(self.tid_name)
d1 = self.send_message(self.rq_exchange, route, reply,
tid=tid)
d1.addErrback(self._error)
if not self.no_ack:
self.client.basic_ack(msg)
return d1
def _read_new(_none):
if not self.parallel and not self._stopping:
reactor.callLater(0, self.read_message_loop)
d.addCallback(_push_message)
if not self.parallel:
d.addCallback(_read_new)
d.addErrback(self._error)
return d
示例14: handle_images
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addErrback [as 别名]
def handle_images(result):
if result[0] == 0:
image_list = result[1]
##
## Find the image we're reindexing, and bump it's index by .1
##
for image in image_list:
if image['image_id'] == image_id:
if image['media_idx'] > new_idx:
image['media_idx'] = float(new_idx)-.1
else:
image['media_idx'] = float(new_idx)+.1
##
## Now, resort the image list.
##
self.log.debug("before sort: %s" % pformat(image_list))
image_list.sort(lambda a, b: cmp(a['media_idx'], b['media_idx']))
self.log.debug("after sort: %s" % pformat(image_list))
##
## The images are now in the proper order. This loop starts at
## 0 and updates each image's index, if necessary. If the new index
## matches the old index, nothing happens.
##
d3 = Deferred()
for image in image_list:
d3.addCallback(act_order, image)
d3.callback(0)
d3.addCallback(lambda _: (0, "success"))
d3.addErrback(lambda _: (-1, _.getErrorMessage()))
return d3
else:
return result
示例15: get_response
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addErrback [as 别名]
def get_response(cmd_data):
for cmd in cmd_data :
def __command_done(result, command) :
res = result
if not isinstance(result, CommandResult) :
res = CommandResult(status = result)
self.factory.next_state(ProtocolState.Report, ReportData(command, res), self.transport.connector)
ok_func = partial(__command_done, command = cmd)
def __command_error(reason, command):
res = CommandResult('Failed', str(reason))
self.factory.next_state(ProtocolState.Report, ReportData(command, res), self.transport.connector)
err_func = partial(__command_error, command = cmd)
# Obtain only new commands next time
if self.factory.timestamp is not None :
self.factory.timestamp = max(self.factory.timestamp, self._parse_date(cmd['timestamp']))
else :
self.factory.timestamp = self._parse_date(cmd['timestamp'])
# DeviceDelegate has to use this deferred object to notify us that command processing finished.
cmd_defer = Deferred()
cmd_defer.addCallback(ok_func)
cmd_defer.addErrback(err_func)
# Actual run of command
try :
self.factory.device_delegate.do_command(cmd, cmd_defer)
except Exception, err :
log.err('Failed to execute device-delegate do_command. Reason: <{0}>.'.format(err))
err_func(err)