2017-10-18 69 views
0

我有一個類,它被註釋爲@ defer.inlineCallbacks (我想返回從這個機器列表)如何從Python中的延遲方法/扭曲的分配返回值

@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>。我如何閱讀清單?

回答

0

inlineCallbacks只是與Deferred一起使用的替代API。

您已經成功使用inlineCallbacks以避免編寫回調函數。儘管你忘了使用returnValue。替換:

yield self.machineList 

defer.returnValue(self.machineList) 

不能解決你問這個問題,雖然。 inlineCallbacks給你一個不同的API 裏面的它裝飾的功能 - 但不在外面。正如你所注意到的,如果你調用一個裝飾它的函數,你會得到一個Deferred

添加回調(和errback可,最終)至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()