本文整理汇总了Python中twisted.internet.defer.Deferred类的典型用法代码示例。如果您正苦于以下问题:Python Deferred类的具体用法?Python Deferred怎么用?Python Deferred使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Deferred类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: send_command
def send_command(self, command, expect='OK'):
self.log('Sending: %r' % (command,))
resp = Deferred()
resp.addCallback(self.debug)
self.deferreds.append((expect, resp))
self.sendLine(command)
return resp
示例2: test_processTransportInterface
def test_processTransportInterface(self):
"""
L{IReactorProcess.spawnProcess} connects the protocol passed to it
to a transport which provides L{IProcessTransport}.
"""
ended = Deferred()
protocol = _ShutdownCallbackProcessProtocol(ended)
reactor = self.buildReactor()
transport = reactor.spawnProcess(
protocol, sys.executable, [sys.executable, "-c", ""],
usePTY=self.usePTY)
# The transport is available synchronously, so we can check it right
# away (unlike many transport-based tests). This is convenient even
# though it's probably not how the spawnProcess interface should really
# work.
# We're not using verifyObject here because part of
# IProcessTransport is a lie - there are no getHost or getPeer
# methods. See #1124.
self.assertTrue(IProcessTransport.providedBy(transport))
# Let the process run and exit so we don't leave a zombie around.
ended.addCallback(lambda ignored: reactor.stop())
self.runReactor(reactor)
示例3: get_package
def get_package(self, request, from_ip=None):
commands = self._parse_request(request)
d = Deferred()
d.callback(commands)
return d
示例4: connect
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)
示例5: becomeGridHost
def becomeGridHost(self, *args):
if self.clientObject.getLocalUser().gridHost:
for uuid in self.clientObject.users:
if self.clientObject.users[uuid].gridHostActive:
#TODO: Allow moderators to take gridhost from others.
showModalDialog(
self.window,
Gtk.MessageType.ERROR,
'The grid is already being hosted.'
)
return
#TODO: Show error dialogs on failures
self.setStatus('Loading OpenSim distribution...')
distribution = Distribution(self.clientObject.projectRoot, self.clientObject.externalhost, parent=self.window)
d = Deferred()
d.addCallback(self.startRobust)
distribution.load(d)
#TODO: Don't hardcode this
else:
showModalDialog(
self.window,
Gtk.MessageType.ERROR,
'You do not have permission to become the grid host.'
)
示例6: do_host_count
def do_host_count(self, request, params = {}):
"""
Because process_host_count above is meant to handle its
own finalization, do_host_count always returns NOT_DONE_YET. Its
much simpler to make a tiny hack then hack process_host count to straddle
to different scenarios ( return string and process itself )
"""
#if this a polling request and it's not the first one
if 'ts' in params and params['ts'] != 0:
#if the caller is up to date or from the future
if params['ts'] > self.myStore.lastChange:
#hold the connection open
d = Deferred()
def deferred_host_count(self, request):
request.write(self.process_host_count)
request.finish()
#and notify them when something changes
d.addCallback(self.deferred_host_count, request)
self.myStore.onChange.observe(d)
return NOT_DONE_YET
#If no TS or TS is out of date, process NOW
return self.process_host_count(request)
示例7: test_rewind_stops_on_error
def test_rewind_stops_on_error(self):
"""
rewind errbacks it's completion deferred when it encounters an
error.
"""
called = [0]
def op(op_d):
called[0] += 1
return op_d
self.undo.push(op, None)
op_d1 = Deferred()
self.undo.push(op, op_d1)
d = self.undo.rewind()
self.assertNoResult(d)
class DummyOpFailure(Exception):
pass
op_d1.errback(DummyOpFailure())
self.assertEqual(called[0], 1)
self.failureResultOf(d, DummyOpFailure)
示例8: execute_config
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))
示例9: TorIRC
class TorIRC(IRCClient):
nickname = 'txsocksx-tor-irc'
nickservPassword = ''
def connectionMade(self):
self.sendLine('CAP REQ :sasl')
self.deferred = Deferred()
IRCClient.connectionMade(self)
def irc_CAP(self, prefix, params):
if params[1] != 'ACK' or params[2].split() != ['sasl']:
print 'sasl not available'
self.quit('')
sasl = ('{0}\0{0}\0{1}'.format(self.nickname, self.nickservPassword)).encode('base64').strip()
self.sendLine('AUTHENTICATE PLAIN')
self.sendLine('AUTHENTICATE ' + sasl)
def irc_903(self, prefix, params):
self.sendLine('CAP END')
def irc_904(self, prefix, params):
print 'sasl auth failed', params
self.quit('')
irc_905 = irc_904
def connectionLost(self, reason):
self.deferred.errback(reason)
def signedOn(self):
print 'signed on successfully'
self.quit('')
示例10: testTriggerSystemEvent2
def testTriggerSystemEvent2(self):
# one of the "before" trigger functions returns a deferred. A later
# "before" trigger fires the deferred. A third before runs. Then a
# "during" should be run. One of the failure modes for the old
# cReactor code is to start the "during" as soon as the deferred
# fires, rather than waiting for the "before" phase to be finished
l = []
d = Deferred()
d2 = Deferred()
def _returnDeferred(d=d):
return d
def _fireDeferred(d=d):
d.callback(None)
def _returnDeferred2(d2=d2):
return d2
def _appendToList(l=l):
l.append(1)
r = reactor
# to test this properly, the triggers must fire in this sequence:
# _returnDeferred, _fireDeferred, _returnDeferred2 . cReactor happens
# to run triggers in the order in which they were added.
self.addTrigger("before", "defer2", _returnDeferred)
self.addTrigger("before", "defer2", _fireDeferred)
self.addTrigger("before", "defer2", _returnDeferred2)
self.addTrigger("during", "defer2", _appendToList)
self.addTrigger("after", "defer2", _appendToList)
r.fireSystemEvent("defer2")
self.assertEquals(len(l), 0, "Event should not have fired yet.")
d2.callback(None)
self.assertEquals(len(l), 2)
示例11: test_full_run
def test_full_run(self):
"""Verify a functional agent start via the 'run' method.
This test requires Zookeeper running on the default port of localhost.
The mocked portions are to prevent the daemon start from altering the
test environment (sys.stdout/sys.stderr, and reactor start).
"""
zookeeper.set_debug_level(0)
started = Deferred()
class DummyAgent(BaseAgent):
started = False
def start(self):
started.callback(self)
def validate_started(agent):
self.assertTrue(agent.client.connected)
started.addCallback(validate_started)
pid_file = self.makeFile()
self.change_args("es-agent", "--zookeeper-servers", get_test_zookeeper_address(), "--pidfile", pid_file)
runner = self.mocker.patch(AgentRunner)
logger = self.mocker.patch(AppLogger)
logger.start(MATCH_APP)
runner.startReactor(None, sys.stdout, sys.stderr)
logger.stop()
self.mocker.replay()
DummyAgent.run()
return started
示例12: testChildResolve
def testChildResolve(self):
# I've seen problems with reactor.run under gtk2reactor. Spawn a
# child which just does reactor.resolve after the reactor has
# started, fail if it does not complete in a timely fashion.
helperPath = os.path.abspath(self.mktemp())
helperFile = open(helperPath, 'w')
# Eeueuuggg
reactorName = reactor.__module__
helperFile.write(resolve_helper % {'reactor': reactorName})
helperFile.close()
env = os.environ.copy()
env['PYTHONPATH'] = os.pathsep.join(sys.path)
helperDeferred = Deferred()
helperProto = ChildResolveProtocol(helperDeferred)
reactor.spawnProcess(helperProto, sys.executable, ("python", "-u", helperPath), env)
def cbFinished((reason, output, error)):
# If the output is "done 127.0.0.1\n" we don't really care what
# else happened.
output = ''.join(output)
if output != 'done 127.0.0.1\n':
self.fail((
"The child process failed to produce the desired results:\n"
" Reason for termination was: %r\n"
" Output stream was: %r\n"
" Error stream was: %r\n") % (reason.getErrorMessage(), output, ''.join(error)))
helperDeferred.addCallback(cbFinished)
return helperDeferred
示例13: testTriggerSystemEvent3
def testTriggerSystemEvent3(self):
# make sure reactor can survive the loss of an event type while
# waiting for a before-trigger's Deferred to fire
l = []
d = Deferred()
d2 = Deferred()
def _returnDeferred(d=d):
return d
def _appendToList(l=l):
l.append(1)
def _ignore(failure):
return None
r = reactor
b1 = self.addTrigger("before", "defer3", _returnDeferred)
b2 = self.addTrigger("after", "defer3", _appendToList)
r.fireSystemEvent("defer3")
self.assertEquals(len(l), 0, "Event should not have fired yet.")
self.removeTrigger(b1)
self.removeTrigger(b2)
try:
d.callback(None) # cReactor gives errback to deferred
except ValueError:
pass
self.assertEquals(len(l), 0)
d.addErrback(_ignore)
示例14: get
def get(self, tid):
""" Used to get a token by the BaseHandler, and whenever a
handler needs to token (usually because it wants to access
the store object).
tid -- The ID of the Token to get, it must have already been
created, usually by the get_token call to the AuthHandler.
"""
return_d = Deferred()
if self.tokens.get(tid) is not None:
# already in cache, return existing
return_d.callback(self.tokens.get(tid))
return return_d
# otherwise check the db
def token_cb(token_tuple):
if token_tuple is None:
return_d.callback(None)
return
username, password, boxid, appid, origin, clientip, server_id = token_tuple
token = Token(self.db, username, password, boxid, appid, origin, clientip, server_id)
self.add(token)
return_d.callback(token)
return
self.db.get_token(tid).addCallbacks(token_cb, return_d.errback)
return return_d
示例15: test_disconnectedOnError
def test_disconnectedOnError(self):
"""
If the event handler raises an exception, the event is removed from the
reactor and the handler's C{connectionLost} method is called in the I/O
thread and the exception is logged.
"""
reactorThreadID = getThreadID()
reactor = self.buildReactor()
event = win32event.CreateEvent(None, False, False, None)
result = []
finished = Deferred()
finished.addBoth(result.append)
finished.addBoth(lambda ignored: reactor.stop())
listener = Listener(finished)
reactor.addEvent(event, listener, 'brokenOccurred')
reactor.callWhenRunning(win32event.SetEvent, event)
self.runReactor(reactor)
self.assertIsInstance(result[0], Failure)
result[0].trap(RuntimeError)
self.assertEqual(reactorThreadID, listener.connLostThreadID)
self.assertEqual(1, len(self.flushLoggedErrors(RuntimeError)))