Instance parsing the use of deferred objects in Python's twisted framework

Source: Internet
Author: User
Deferred object structure
Deferred consists of a series of paired callback chains, each of which contains a callback (callbacks) to handle the success and a callback (Errbacks) to handle the error. In the initial state, the deffereds will consist of two empty callback chains. When you add a callback to it, it is always added in pairs. When the results in asynchronous processing are returned, deferred will start and trigger the callback chain in the order in which it was added.
Examples may be easier to illustrate, first look at Addcallback:

From Twisted.internet.defer import Deferred  def mycallback (result):  print result  D = Deferred () D.addcallback (Mycallback) d.callback ("triggering callback.")

Running it will get the following result:

Triggering callback.

In the example above, a deffered is created and its Addcallback method is used to register a callback for processing success. D.callback will start deffered and call the callback chain. The parameters passed into the callback are also received by the first function in each callback chain.
There is addcallback, that other wrong branch, I think I can guess that is adderrorback, also 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."))

Running it will get the following result:

[Failure Instance:traceback (Failure with no frames): <type ' exceptions. ValueError ';: Triggering errback.

It can be seen that twisted the error in failure.
It is important to note that the registration callbacks mentioned earlier are always paired. When using the D.addcallback and D.adderrorback methods, we appear to have just added a callback or a errback. In fact, in order to complete this level of callback chain creation, these methods will also register a pass-through for the other half. Remember that the callback chain always has the same length. If you want to specify callback and Errback for this level of callbacks separately. You can use the D.addcallbacks method:

D = Deferred () d.addcallbacks (Mycallback, Myerrback) d.callback ("triggering callback.")

So... We'll be here before today.

Step-by-step example
The next step should be a bit more practical, that is, put 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) >:      self.d.errback (Exception ("The headline" '%s ' is too long! "% (Headline,)))    Else:      self.d.callback (Headline)    def _tohtml (self, result):    return "

The previous example receives a caption and processes it, and if the title is too long it returns an extra-long error, otherwise it is converted to HTML and returned.

Because the caption given is less than 50 characters, executing the above code will return the following:


It is worth noting that the reactor Calllater method is used to perform timed events to simulate an asynchronous request.

If we make the title very long, for example say:

h = headlineretriever () d = h.getheadline ("1234567890" *6) d.addcallbacks (Printdata, Printerror)

The result can be met:

[Failure Instance:traceback (Failure with no frames): <type ' exceptions. Exception ': The headline ' 123456789012345678901234567890123456789012345678901234567890 ' is too long!]

Let's take a look at the triggering process:

Key points in Deferreds
1. The deferreds will be triggered when it calls its callback or errback;
2. Deferreds can only be triggered once! An attempt to fire multiple times will result in a Alreadycallederror exception;
3. The exceptions in the nth level callback or Errback will be passed into n+1 at errback level, and if there is no errback, The unhandled Error will be thrown. If the nth level callback or Errback does not throw the exception or returns the failure object, then the n+1 in the callback level will be processed;
4. Results returned in callback will be passed to the next level callback , and as its first argument;
5. If the error passed in Errback is not a failure object, it will be automatically wrapped once.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.