2017-10-18 4 views
0

I @ 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 

Iを(私はこれからマシンリストを返したい)を持ちます別の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が得られます。

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() 
関連する問題