本文整理汇总了Python中twisted.internet.defer.DeferredList方法的典型用法代码示例。如果您正苦于以下问题:Python defer.DeferredList方法的具体用法?Python defer.DeferredList怎么用?Python defer.DeferredList使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twisted.internet.defer
的用法示例。
在下文中一共展示了defer.DeferredList方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: tearDown
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import DeferredList [as 别名]
def tearDown(self):
if self.agent:
# clean up connections for twisted.web.client.Agent test.
self.agent.closeCachedConnections()
self.agent = None
# If the test indicated it might leave some server-side connections
# around, clean them up.
connections = list(self.wrapper.protocols.keys())
# If there are fewer server-side connections than requested,
# that's okay. Some might have noticed that the client closed
# the connection and cleaned up after themselves.
for n in range(min(len(connections), self.cleanupServerConnections)):
proto = connections.pop()
msg("Closing %r" % (proto,))
proto.transport.abortConnection()
d = self.port.stopListening()
return defer.DeferredList([waitUntilAllDisconnected(
reactor, list(self.wrapper.protocols.keys())), d])
示例2: test_errors
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import DeferredList [as 别名]
def test_errors(self):
"""
Verify that for each way a method exposed via XML-RPC can fail, the
correct 'Content-type' header is set in the response and that the
client-side Deferred is errbacked with an appropriate C{Fault}
instance.
"""
dl = []
for code, methodName in [(666, "fail"), (666, "deferFail"),
(12, "fault"), (23, "noSuchMethod"),
(17, "deferFault"), (42, "SESSION_TEST")]:
d = self.proxy().callRemote(methodName)
d = self.assertFailure(d, xmlrpc.Fault)
d.addCallback(lambda exc, code=code:
self.assertEqual(exc.faultCode, code))
dl.append(d)
d = defer.DeferredList(dl, fireOnOneErrback=True)
def cb(ign):
for factory in self.factories:
self.assertEqual(factory.headers[b'content-type'],
b'text/xml; charset=utf-8')
self.flushLoggedErrors(TestRuntimeError, TestValueError)
d.addCallback(cb)
return d
示例3: testResults
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import DeferredList [as 别名]
def testResults(self):
inputOutput = [
("add", (2, 3), 5),
("defer", ("a",), "a"),
("dict", ({"a": 1}, "a"), 1),
("triple", ("a", 1), ["a", 1, None])]
dl = []
for meth, args, outp in inputOutput:
d = self.proxy().callRemote(meth, *args)
d.addCallback(self.assertEqual, outp)
dl.append(d)
# SOAPpy kinda blows.
d = self.proxy().callRemote('complex')
d.addCallback(lambda result: result._asdict())
d.addCallback(self.assertEqual, {"a": ["b", "c", 12, []], "D": "foo"})
dl.append(d)
# We now return to our regularly scheduled program, already in progress.
return defer.DeferredList(dl, fireOnOneErrback=True)
示例4: logOn
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import DeferredList [as 别名]
def logOn(self, chatui):
"""
@returns: this breaks with L{interfaces.IAccount}
@returntype: DeferredList of L{interfaces.IClient}s
"""
# Overriding basesupport's implementation on account of the
# fact that _startLogOn tends to return a deferredList rather
# than a simple Deferred, and we need to do registerAccountClient.
if (not self._isConnecting) and (not self._isOnline):
self._isConnecting = 1
d = self._startLogOn(chatui)
d.addErrback(self._loginFailed)
def registerMany(results):
for success, result in results:
if success:
chatui.registerAccountClient(result)
self._cb_logOn(result)
else:
log.err(result)
d.addCallback(registerMany)
return d
else:
raise error.ConnectionError("Connection in progress")
示例5: _cbGetFileSize
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import DeferredList [as 别名]
def _cbGetFileSize(self, attrs, rf, lf):
if not stat.S_ISREG(attrs['permissions']):
rf.close()
lf.close()
return "Can't get non-regular file: %s" % rf.name
rf.size = attrs['size']
bufferSize = self.client.transport.conn.options['buffersize']
numRequests = self.client.transport.conn.options['requests']
rf.total = 0.0
dList = []
chunks = []
startTime = self.reactor.seconds()
for i in range(numRequests):
d = self._cbGetRead('', rf, lf, chunks, 0, bufferSize, startTime)
dList.append(d)
dl = defer.DeferredList(dList, fireOnOneErrback=1)
dl.addCallback(self._cbGetDone, rf, lf)
return dl
示例6: testDeferredListWithAlreadyFiredDeferreds
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import DeferredList [as 别名]
def testDeferredListWithAlreadyFiredDeferreds(self):
# Create some deferreds, and err one, call the other
d1 = defer.Deferred()
d2 = defer.Deferred()
d1.errback(GenericError('Bang'))
d2.callback(2)
# *Then* build the DeferredList
dl = defer.DeferredList([d1, d2])
result = []
dl.addCallback(result.append)
self.assertEqual(1, len(result))
d1.addErrback(lambda e: None) # Swallow error
示例7: test_cancelDeferredListCallback
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import DeferredList [as 别名]
def test_cancelDeferredListCallback(self):
"""
When cancelling an unfired L{defer.DeferredList} without the
C{fireOnOneCallback} and C{fireOnOneErrback} flags set, the
L{defer.DeferredList} will be callback with a C{list} of
(success, result) C{tuple}s.
"""
deferredOne = defer.Deferred(fakeCallbackCanceller)
deferredTwo = defer.Deferred()
deferredList = defer.DeferredList([deferredOne, deferredTwo])
deferredList.cancel()
self.failureResultOf(deferredTwo, defer.CancelledError)
result = self.successResultOf(deferredList)
self.assertTrue(result[0][0])
self.assertEqual(result[0][1], "Callback Result")
self.assertFalse(result[1][0])
self.assertTrue(result[1][1].check(defer.CancelledError))
示例8: test_cancelDeferredListWithFireOnOneErrback
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import DeferredList [as 别名]
def test_cancelDeferredListWithFireOnOneErrback(self):
"""
When cancelling an unfired L{defer.DeferredList} with the flag
C{fireOnOneErrback} set, cancel every L{defer.Deferred} in the list.
"""
deferredOne = defer.Deferred()
deferredTwo = defer.Deferred()
deferredList = defer.DeferredList([deferredOne, deferredTwo],
fireOnOneErrback=True)
deferredList.cancel()
self.failureResultOf(deferredOne, defer.CancelledError)
self.failureResultOf(deferredTwo, defer.CancelledError)
deferredListFailure = self.failureResultOf(deferredList,
defer.FirstError)
firstError = deferredListFailure.value
self.assertTrue(firstError.subFailure.check(defer.CancelledError))
示例9: test_cancelDeferredListWithFireOnOneErrbackAllDeferredsCallback
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import DeferredList [as 别名]
def test_cancelDeferredListWithFireOnOneErrbackAllDeferredsCallback(self):
"""
When cancelling an unfired L{defer.DeferredList} with the flag
C{fireOnOneErrback} set, if all the L{defer.Deferred} callbacks
in its canceller, the L{defer.DeferredList} will callback with a
C{list} of (success, result) C{tuple}s.
"""
deferredOne = defer.Deferred(fakeCallbackCanceller)
deferredTwo = defer.Deferred(fakeCallbackCanceller)
deferredList = defer.DeferredList([deferredOne, deferredTwo],
fireOnOneErrback=True)
deferredList.cancel()
result = self.successResultOf(deferredList)
self.assertTrue(result[0][0])
self.assertEqual(result[0][1], "Callback Result")
self.assertTrue(result[1][0])
self.assertEqual(result[1][1], "Callback Result")
示例10: test_cancelDeferredListWithException
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import DeferredList [as 别名]
def test_cancelDeferredListWithException(self):
"""
Cancelling a L{defer.DeferredList} will cancel every L{defer.Deferred}
in the list even exceptions raised from the C{cancel} method of the
L{defer.Deferred}s.
"""
def cancellerRaisesException(deferred):
"""
A L{defer.Deferred} canceller that raises an exception.
@param deferred: The cancelled L{defer.Deferred}.
"""
raise RuntimeError("test")
deferredOne = defer.Deferred(cancellerRaisesException)
deferredTwo = defer.Deferred()
deferredList = defer.DeferredList([deferredOne, deferredTwo])
deferredList.cancel()
self.failureResultOf(deferredTwo, defer.CancelledError)
errors = self.flushLoggedErrors(RuntimeError)
self.assertEqual(len(errors), 1)
示例11: testCooperation
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import DeferredList [as 别名]
def testCooperation(self):
L = []
def myiter(things):
for th in things:
L.append(th)
yield None
groupsOfThings = ['abc', (1, 2, 3), 'def', (4, 5, 6)]
c = task.Cooperator()
tasks = []
for stuff in groupsOfThings:
tasks.append(c.coiterate(myiter(stuff)))
return defer.DeferredList(tasks).addCallback(
lambda ign: self.assertEqual(tuple(L), sum(zip(*groupsOfThings), ())))
示例12: test_failedCertificateVerification
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import DeferredList [as 别名]
def test_failedCertificateVerification(self):
"""
Check that connecting with a certificate not accepted by the server CA
fails.
"""
onServerLost = defer.Deferred()
onClientLost = defer.Deferred()
self.loopback(sslverify.OpenSSLCertificateOptions(privateKey=self.sKey,
certificate=self.sCert, verify=False,
requireCertificate=False),
sslverify.OpenSSLCertificateOptions(verify=True,
requireCertificate=False, caCerts=[self.cCert]),
onServerLost=onServerLost,
onClientLost=onClientLost)
d = defer.DeferredList([onClientLost, onServerLost],
consumeErrors=True)
def afterLost(result):
((cSuccess, cResult), (sSuccess, sResult)) = result
self.assertFalse(cSuccess)
self.assertFalse(sSuccess)
return d.addCallback(afterLost)
示例13: test_callFromThread
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import DeferredList [as 别名]
def test_callFromThread(self):
"""
Test callFromThread functionality: from the main thread, and from
another thread.
"""
def cb(ign):
firedByReactorThread = defer.Deferred()
firedByOtherThread = defer.Deferred()
def threadedFunc():
reactor.callFromThread(firedByOtherThread.callback, None)
reactor.callInThread(threadedFunc)
reactor.callFromThread(firedByReactorThread.callback, None)
return defer.DeferredList(
[firedByReactorThread, firedByOtherThread],
fireOnOneErrback=True)
return self._waitForThread().addCallback(cb)
示例14: deferredDict
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import DeferredList [as 别名]
def deferredDict(d):
"""
Just like a :class:`defer.DeferredList` but instead accepts and returns a :class:`dict`.
Args:
d: A :class:`dict` whose values are all :class:`defer.Deferred` objects.
Returns:
:class:`defer.DeferredList` whose callback will be given a dictionary whose
keys are the same as the parameter :obj:`d` and whose values are the results
of each individual deferred call.
"""
if len(d) == 0:
return defer.succeed({})
def handle(results, names):
rvalue = {}
for index in range(len(results)):
rvalue[names[index]] = results[index][1]
return rvalue
dl = defer.DeferredList(d.values())
return dl.addCallback(handle, d.keys())
示例15: _add_nodes_to_cluster
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import DeferredList [as 别名]
def _add_nodes_to_cluster(self, reactor, cluster, results):
def add_node(node, index):
# The control should be already fully configured.
if node is not cluster.control_node:
return self._add_node_to_cluster(reactor, cluster, node, index)
for i, d in enumerate(results):
d.addCallback(add_node, i)
# Failure to add any one node to a cluster is not fatal,
# we are happy with a partial success as long as we've
# managed to configure the control node.
# So, just wait until we are done with all nodes.
d = DeferredList(results)
d.addCallback(lambda _: cluster)
return d