Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

Lintel Technologies: InlineCallbacks

$
0
0

Twisted features a decorator named inlineCallbacks which allows you to work with deferreds without writing callback functions.

This is done by writing your code as generators, which yield deferreds instead of attaching callbacks.

Consider the following function written in the traditional deferred style:

importtxredisapias redis fromtwisted.internetimportdefer fromtwisted.internetimportreactor defmain(): rc = redis.Connection() printrc rc.addCallback(onSuccess) rc.addErrback(onFail) defonSuccess(result): print "Success : " printresult defonFail(result): print "Fail : " printresult if __name__ == '__main__': main() reactor.run()

using inlineCallbacks, we can write this as:

from twisted.internet.defer import inlineCallbacks

importtxredisapias redis fromtwisted.internetimportdefer fromtwisted.internetimportreactor @defer.inlineCallbacks defmain(): rc = yieldredis.Connection() printrc yieldrc.set("abc", "pqr") v = yieldrc.get("abc") print "value : ", repr(v) yieldrc.disconnect() if __name__ == "__main__": main() reactor.run()

Instead of calling addCallback on the deferred returned by redis.Connection, we yield it. this causes Twisted to return the deferred‘s result to us.

Though the inlineCallbacks looks like synchronous code, which blocks while waiting for the request to finish, each yield statement allows other code to run while waiting for the deferred being yielded to fire.

inlineCallbacks become even more powerful when dealing with complex control flow and error handling.


Viewing all articles
Browse latest Browse all 9596

Trending Articles