Twisted的inlineCallbacks

關(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í)行。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容