[英]how to get value from returned instance of deferred
我使用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"
如果要以扭曲的方式編寫異步代碼,看起來更像是同步的代碼,請嘗試使用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")
如果要從延期中獲取實際值,則可以在結果可用后使用。 變得可用需要多長時間取決於它正在等待什么。
看下面的例子。 結果可用之前有任意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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.