2016-09-15 8 views
0

私はtongmongo libをmongoDBのドライバとして使用します。 限られたドキュメントでは、txmongoのfind関数は遅延のインスタンスを返しますが、実際の結果({"IP":11.12.59.119}など)を得るにはどうすればいいですか?私はyield、str()とrepr()を試しましたが動作しません。返されたインスタンスから値を取得する方法

def checkResource(self, resource): 
    """ use the message to inquire database 
     then set the result to a ip variable 
    """ 
    d = self.units.find({'$and': [{'baseIP':resource},{'status':'free'}]},limit=1,fields={'_id':False,'baseIP':True}) 
    #Here above, how can I retrieve the result in this deferred instance?? 
    d.addCallback(self.handleReturnedValue) 
    d.addErrback(log.err) 
    return d 

def handleReturnedValue(self, returned): 
    for ip in returned: 
     if ip is not None: 
      d = self.updateData(ip,'busy') 
      return d 
     else: 
      return "NA" 
+0

あなたは値がhandleReturnedValueのHTTPSでアクセスできるように、コールバックを使用する必要があります。 com/documents/16.0.0/core/howto/defer.html –

答えて

1

あなたはより多くの同期のように見えるツイストで非同期コードを書きたい場合は、defer.inlineCallbacks

これは、ドキュメントからのもので使用してみてください: http://twisted.readthedocs.io/en/twisted-16.2.0/core/howto/defer-intro.html#inline-callbacks-using-yield

は伝統的に書かれた次の関数を考えてみましょうを据え置き スタイル:

inlineCallbacksを使用して

、我々はこれを書くことができます。

from twisted.internet.defer import inlineCallbacks, returnValue 

@inlineCallbacks 
def getUsers(self): 
    responseBody = yield makeRequest("GET", "/users") 
    returnValue(json.loads(responseBody)) 

EDIT:// twistedmatrix:

def checkResource(self, resource): 
    """ use the message to inquire database 
     then set the result to a ip variable 
    """ 
    returned = yield self.units.find({'$and': [{'baseIP':resource},{'status':'free'}]},limit=1,fields={'_id':False,'baseIP':True}) 
    # replacing callback function 
    for ip in returned: 
     if ip is not None: 
      d = self.updateData(ip,'busy') # if this returns deferred use yield again 
      returnValue(d)    
    returnValue("NA") 
+0

私はそれをジェネレータにすると、プログラムはこのcheckResource関数に全く入っていません。 – Henry

+0

デコレータを楽しく設定しましたか? ction? –

+0

いいえこれを追加した後でもう一度やり直してみてください。少なくともリストタイプのオブジェクトがあるようです。しかし、どうすれば関数を変更できますか?遅延インスタンスを返すはずだったので、今度は他のオブジェクトを返します。 – Henry

関連する問題