【问题标题】:How to assign a returned value from the defer method in python/twisted如何从 python/twisted 中的 defer 方法分配返回值
【发布时间】:2017-10-18 02:01:49
【问题描述】:

我有一个类,注释为@defer.inlineCallbacks (我想从这里返回机器列表)

 @defer.inlineCallbacks
    def getMachines(self):
        serverip = 'xx'
        basedn = 'xx'
        binddn = 'xx'
        bindpw = 'xx'
        query = '(&(cn=xx*)(objectClass=computer))'
        c = ldapconnector.LDAPClientCreator(reactor, ldapclient.LDAPClient)
        overrides = {basedn: (serverip, 389)}
        client = yield c.connect(basedn, overrides=overrides)
        yield client.bind(binddn, bindpw)
        o = ldapsyntax.LDAPEntry(client, basedn)
        results = yield o.search(filterText=query)
        for entry in results:
            for i in entry.get('name'):
                self.machineList.append(i)

        yield self.machineList
        return

我在另一个 python 文件中定义了另一个类,我想在其中调用上述方法并读取 machineList。

returned =  LdapClass().getMachines()   
  print returned

印刷品上写着<Deferred at 0x10f982908>。如何阅读列表?

【问题讨论】:

    标签: python twisted twisted.web


    【解决方案1】:

    inlineCallbacks 只是用于处理Deferred 的备用 API。

    您已经成功地使用了inlineCallbacks 来避免编写回调函数。你忘了使用returnValue。替换:

    yield self.machineList
    

    defer.returnValue(self.machineList)
    

    不过,这并不能解决您所询问的问题。 inlineCallbacks 为您提供了一个不同的 API inside 它所装饰的功能 - 但不在外部。正如你所注意到的,如果你调用一个用它装饰的函数,你会得到一个Deferred

    Deferred 添加一个回调(以及最终的errback):

    returned = LdapClass().getMachines()
    def report_result(result):
        print "The result was", result
    returned.addCallback(report_result)
    returned.addErrback(log.err)
    

    或者多使用inlineCallbacks

    @inlineCallbacks
    def foo():
        try:
            returned = yield LdapClass().getMachines()
            print "The result was", returned
        except:
            log.err()
    

    【讨论】:

      猜你喜欢
      • 2013-11-24
      • 1970-01-01
      • 2022-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-03
      相关资源
      最近更新 更多