如何从返回的延迟实例中获取值

时间:2016-09-15 19:49:14

标签: python mongodb twisted

我使用txmongo lib作为mongoDB的驱动程序。 在其有限的文档中,txmongo中的find函数将返回deferred的实例,但是如何获得实际结果(如{" 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"

2 个答案:

答案 0 :(得分:1)

如果您希望以非常类似于同步的方式编写异步代码,请尝试使用defer.inlineCallbacks

这是来自文档: http://twisted.readthedocs.io/en/twisted-16.2.0/core/howto/defer-intro.html#inline-callbacks-using-yield

  

考虑以传统Deferred编写的以下函数   式:

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")

答案 1 :(得分:0)

如果要从延期中获取实际值,则可以在结果可用之后。可用的时间取决于等待的时间。

看下面的例子。结果可用之前有2秒的任意延迟,因此尝试在访问它之前抛出AttributeError

from twisted.internet import defer, reactor


def getDummyData(inputData):
    """
    This function is a dummy which simulates a delayed result and
    returns a Deferred which will fire with that result. Don't try too
    hard to understand this.

    From Twisted docs
    """
    deferred = defer.Deferred()
    # simulate a delayed result by asking the reactor to fire the
    # Deferred in 2 seconds time with the result inputData * 3
    reactor.callLater(2, deferred.callback, inputData * 3)
    return deferred


d = getDummyData(2)

reactor.callLater(1, lambda: print(d))
# Prints: <Deferred at 0x7f4853ed3550>

reactor.callLater(3, lambda: print(d))
# Prints: <Deferred at 0x7f4853ed3550 current result: 6>

reactor.callLater(3, lambda: print(d.result))
# Prints: 6

# Throws AttributeError because Deferred does not have a result after 1 sec
# reactor.callLater(1, lambda: print(d.result))

reactor.callLater(4, reactor.stop)
reactor.run()