Example Twisted detailed usage in the Python Deferred object frame

Deferred object for Twsited framework for handling callbacks, which for relying on asynchronous Twisted is very important, then we have to resolve examples of usage Python Twisted framework of Deferred object.

Deferred callback chain by a series of pairs, each pair contains a callback (callbacks) for a successful treatment and a callback for handling errors (errbacks). Initially, deffereds by two empty callback chains. It will always be added in pairs when you add a callback to it. When the result of the asynchronous processing of returns, Deferred and will start in the order when the trigger callback added chain.

Perhaps easier to explain with an example, first look addCallback:

from twisted.internet.defer import Deferred
def myCallback(result):
print result
d = Deferred()
d.addCallback(myCallback)
d.callback("Triggering callback.")

Run it will get the following results:

Triggering callback.

The example creates a deffered and use its addCallback method to register a callback for successful treatment. d.callback starts deffered and calls callback chain. Callback parameter will be passed in each first chain callback function receives.

There addCallback, another error that branch, I would like to be able to guess that addErrorback, the same look at an example:

from twisted.internet.defer import Deferred
def myErrback(failure):
print failure
d = Deferred()
d.addErrback(myErrback)
d.errback(ValueError("Triggering errback."))

Run it will get the following results:

[Failure instance: Traceback (failure with no frames): <type 'exceptions.ValueError'>: Triggering errback.]

Twisted error would be seen in the encapsulated Failure.

It is worth noting that the reference had registered before the callback is always paired. When using d.addCallback and d.addErrorback method, we seem just added a callback or a errback.

In fact, in order to complete the creation of this level callback chain, these methods will be for the other half registered a pass-through. Remember, the callback chain always have the same length. If you want to specify a callback this callback and errback respectively.

D.addCallbacks methods can be used:

d = Deferred()
d.addCallbacks(myCallback, myErrback)
d.callback("Triggering callback.")

Then it should be more practical point, that is, into the Reactor.

Let's look at an example:

from twisted.internet import reactor, defer
class HeadlineRetriever(object):
def processHeadline(self, headline):
if len(headline) > 50:
self.d.errback(Exception("The headline ``%s'' is too long!" % (headline,)))
else:
self.d.callback(headline)
def _toHTML(self, result):
return "<h1>%s</h1>" % (result,)
def getHeadline(self, input):
self.d = defer.Deferred()
reactor.callLater(1, self.processHeadline, input)
self.d.addCallback(self._toHTML)
return self.d
def printData(result):
print result
reactor.stop()
def printError(failure):
print failure
reactor.stop()
h = HeadlineRetriever()
d = h.getHeadline("Breaking News: Twisted Takes us to the Moon!")
d.addCallbacks(printData, printError)
reactor.run()

Receiving a title on cases and processes, if the title will return long long error, otherwise it is converted to HTML and back.

The title given by fewer than 50 characters, it will be returned to perform the above code is as follows:

<h1>Breaking News: Twisted Takes us to the Moon!</h1>

It is worth noting, the above method uses callLater the reactor, which can be used for timed events to simulate an asynchronous request.

If we become very long title, for example:

h = HeadlineRetriever()
d = h.getHeadline("1234567890"*6)
d.addCallbacks(printData, printError)

That result can be met

[Failure instance: Traceback (failure with no frames): : The headline ``123456789012345678901234567890123456789012345678901234567890'' is too long!

file

We look at the map to trigger the process:

  • The key point in Deferreds

  • Deferreds will be triggered when you call their callback or errback;

  • Deferreds can only be triggered once! If you try to trigger multiple times will result in AlreadyCalledError abnormal;

  • Errback callback or stage N Exceptions will be passed in a first stage N + errback. 1; and if not errback, is thrown Unhandled Error. If the N-th stage callback errback or no return or throws Exception Failure objects, that will be processed by a subsequent stage N + 1 of the callback;

  • Results callback returned callback will be passed into the next stage, as its first parameter;

  • If the object is not a Failure incoming errback mistake, it will automatically be packed once.

Published 38 original articles · won praise 1 · views 2182

Guess you like

Origin blog.csdn.net/wulishinian/article/details/104970772