问题描述
我有一个课,其注释为@ 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方法分配返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!