如何从python/twisted中的defer方法分配返回值 [英] How to assign a returned value from the defer method in python/twisted

查看:242
本文介绍了如何从python/twisted中的defer方法分配返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

打印中显示<Deferred at 0x10f982908>.如何阅读清单?

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

推荐答案

inlineCallbacks只是与Deferred一起使用的备用API.

inlineCallbacks is just an alternate API for working with Deferred.

大多数情况下,您已经成功使用inlineCallbacks来避免编写回调函数.但是,您忘记了使用returnValue.替换:

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

yield self.machineList

使用

defer.returnValue(self.machineList)

但是,这不能解决您要问的问题. inlineCallbacks为您提供了一个不同的API,内部它装饰的功能-但外部没有.如您所见,如果调用一个用它装饰的函数,则会得到一个Deferred.

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.

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)

或使用inlineCallbacks一些:

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

这篇关于如何从python/twisted中的defer方法分配返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆