Examples of parsing Python Twisted framework Deferred object Usage

Deferred object for use in Twsited framework for handling callbacks, which for relying on asynchronous Twisted is very important, then we Python Twisted framework to resolve instances of objects in Deferred
Deferred object structure
Deferred callback chain by a series of paired composition, each callback (callbacks) to include a process for successful and callback (errbacks) for handling errors. 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.")

Well ... first come here today.
Advanced example
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): <type 'exceptions.Exception'>: The headline ``123456789012345678901234567890123456789012345678901234567890'' is too long!]

We look at the map to trigger the process: Here Insert Picture Description
The key point of Deferreds

  1. Deferreds will be triggered when you call their callback or errback;
  2. Deferreds can only be triggered once! If you try to trigger multiple times will result in AlreadyCalledError abnormal;
  3. 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;
  4. Results callback returned callback will be passed into the next stage, as its first parameter;
  5. If the object is not a Failure incoming errback mistake, it will automatically be packed once.
    Finally, I recommend a good reputation python gathering [ click to enter ], there are a lot of old-timers learning skills, learning experience

, Interview skills, workplace experience and other share, the more carefully prepared the zero-based introductory information, information on actual projects, programmers every day

Python method to explain the timing of technology, to share some of the learning and the need to pay attention to small details

Published 10 original articles · won praise 0 · Views 3948

Guess you like

Origin blog.csdn.net/haoxun11/article/details/104886885