2016-09-15 85 views
0

我使用txmongo 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訪問:// twistedmatrix。 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

考慮寫在傳統的以下功能推遲 風格:

def getUsers(): 
    d = makeRequest("GET", "/users") 
    d.addCallback(json.loads) 
    return d 

使用inlineCallbacks,我們可以寫爲:

from twisted.internet.defer import inlineCallbacks, returnValue 

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

編輯:

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