【问题标题】:Twisted: Waiting for all deferreds to fireTwisted:等待所有延迟触发
【发布时间】:2012-05-27 12:23:27
【问题描述】:

当我从我的测试方法中调用 DoSomething() 方法时,我希望它会阻止 Connect() 中的 yield,但它没有,它返回一个尚未调用的延迟。

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

我怎样才能让它阻塞直到第二个(也是最后一个)延迟被调用?

【问题讨论】:

    标签: python twisted trial


    【解决方案1】:

    您在DoSomething() 中对self.Connect() 的调用应该返回一个尚未解雇的延迟;这就是 inlineCallbacks 的工作原理。 Connect() 开头的代码应该被调用,但是一旦它到达第一个 yield,它就会将它的 Deferred 返回给你的调用者。稍后,当获取 AMQP 通道时,将触发 Deferred。

    如果你想在c Deferred 触发后对DoSomething() 调用...做某事:),并且你不想将DoSomething() 变成另一个 inlineCallbacks 方法,那么只需在正常方式:addCallback() 和朋友们。示例:

    def DoSomething(self):
        c = self.Connect()
        c.addCallback(self.handle_getting_amqp_channel)
        c.addErrback(self.this_gets_called_if_something_went_wrong)
        return c
    

    有关 Twisted Deferreds 如何工作的更多信息,请参阅http://twistedmatrix.com/documents/current/core/howto/defer.html。希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      代码似乎不太清楚(尤其是第 4 行缩进)。 但是,如果我做对了 self.Connect() 调用 returns deferred 本身,所以你必须使用:

      c = yield self.Connect()

      为了防止它在后台运行并将 deferredResult 返回到 c 变量中。

      【讨论】:

      • 抱歉缩进,我已经修好了。无论如何,编写 c = yield self.Connect() 要求我用 @defer.inlineCallbacks 标记 DoSomething() 方法,这就是全部技巧,我正在寻找一种方法来在 Connect() 中使用延迟而不标记调用方法做某事()
      • @fourat 然后唯一明显的方法是向延迟的 c 添加一些回调并通过此回调触发进一步的步骤,例如:`def doNextStep(dfr_result): do_smth()` ` c = self.Connect()` ` c.addCallback(doNextStep)`
      猜你喜欢
      • 1970-01-01
      • 2011-03-31
      • 1970-01-01
      • 1970-01-01
      • 2015-09-04
      • 1970-01-01
      • 2017-05-18
      • 1970-01-01
      • 2013-07-07
      相关资源
      最近更新 更多