How to assign a returned value from the defer method in python/twisted

隐身守侯 提交于 2019-12-12 05:09:56

问题


I have a class, which is annotated as @defer.inlineCallbacks (I want to return the machine list from this)

 @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

I have another class defined in another python file, where i wnat to call above method and read the machineList.

returned =  LdapClass().getMachines()   
  print returned

The print says <Deferred at 0x10f982908>. How can I read the list ?


回答1:


inlineCallbacks is just an alternate API for working with Deferred.

You've mostly successfully used inlineCallbacks to avoid having to write callback functions. You forgot to use returnValue though. Replace:

yield self.machineList

with

defer.returnValue(self.machineList)

This does not fix the problem you're asking about, though. inlineCallbacks gives you a different API inside the function it decorates - but not outside. As you've noticed, if you call a function decorated with it, you get a Deferred.

Add a callback (and an errback, eventually) to the Deferred:

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

Or use inlineCallbacks some more:

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


来源:https://stackoverflow.com/questions/46801724/how-to-assign-a-returned-value-from-the-defer-method-in-python-twisted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!