当我从我的测试方法调用DoSomething()方法时,我希望它在Connect()中阻塞yield,但它没有,它返回一个not called yet deferred。在
Class Foo:
@defer.inlineCallbacks
def Connect(self):
amqpConfig = AmqpConfig(self.config.getConfigFile())
self.amqp = AmqpFactory(amqpConfig)
try:
# First Deferred
d = self.amqp.connect()
# Second Deferred
d.addCallback(lambda ign: self.amqp.getChannelReadyDeferred())
# Block until connecting and getting an AMQP channel
yield d
except Exception, e:
self.log.error('Cannot connect to AMQP broker: %s', e)
def DoSomething(self):
c = self.Connect()
# None of the deferreds were fired, c.called is False
在调用第二个(也是最后一个)deferred之前,如何让它阻塞?在
代码看起来有点不清楚(尤其是第四行的缩进)。 但是,如果我做对了自我连接()调用返回a延迟的本身,因此您必须使用:
c=产量自我连接()
为了防止它在后台运行,并将deferredResult返回到c变量中。在
您对
DoSomething()
中的self.Connect()
的调用是假定返回尚未触发的延迟;这就是内联回调的工作原理。应该调用Connect()
开头的代码,但是一旦它碰到第一个yield
,它就把它的Deferred返回给调用者。稍后,当获得AMQP信道时,延迟的信道将被触发。在如果您希望
DoSomething()
调用。。。请执行以下操作:)在c
延迟激发之后,并且您不希望将DoSomething()
变成另一个内联回调方法,那么只需以正常方式使用延迟的:addCallback()
和friends。示例:有关Twisted Deferreds如何工作的详细信息,请参见http://twistedmatrix.com/documents/current/core/howto/defer.html。希望这有帮助。在
相关问题 更多 >
编程相关推荐