關(guān)于 Twisted的inlineCallbacks
簡單理解
正如文檔中所說inlineCallbacks可以幫助你使用看起來像有規(guī)整的順序的函數(shù)代碼去寫回調(diào)函數(shù)Deferred.
如下小例子:
import sys
import time
from twisted.python import log
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks, returnValue
log.startLogging(sys.stdout)
class Section(object):
def __init__(self):
self.sentence = "I'm now in Methods: "
@inlineCallbacks
def run(self):
sections = ['audio', 'upload']
for stage, name in enumerate(sections, 1):
method = 'section_%s' % name
result = yield getattr(self, method)()
print(result)
print('Now the stage: {}'.format(stage))
@inlineCallbacks
def section_audio(self):
time.sleep(3)
r = yield self.sentence + 'audio...'
returnValue(r)
@inlineCallbacks
def section_upload(self):
time.sleep(2)
r = yield self.sentence + 'upload...'
returnValue(r)
if __name__ == '__main__':
s = Section()
s.run()
reactor.run()
如上邊小例子,使用inlineCallbacks可以將twisted的任務(wù),按照我們所寫的代碼順序運(yùn)行。而在使用inlineCallbacks時(shí),需要函數(shù)返回一個(gè)生成器,所以我們使用yield。因?yàn)?code>inlineCallbacks是把生成器變成一系列的callbacks進(jìn)行執(zhí)行。