Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Ok, a whole new answer to explain better how <a href="http://twistedmatrix.com/documents/11.0.0/api/twisted.internet.defer.Deferred.html" rel="nofollow">deferreds</a> work. You should think, at least I do, the flow of the program as a state machine. A success or a failure is like an input of that machine that, potentially, change the state. In your case you have two states, logged and non logged, and three inputs: successfully logged in, wrong authentication and could not logged for server problems. Only one of this inputs is recoverable, the case the server could not login the user for same strange problem and in this case you can recover the problem retrying the login. Here the new code:</p> <pre><code>import sys from twisted.internet import reactor, defer class FourOhFourError(Exception): pass class AuthenticationError(Exception): pass def logon(retry=3, success=2, wrong_auth=0): # do stuff d = defer.Deferred() # not_found is the only error recoverable d.addErrback(not_found, retry, success) if wrong_auth: reactor.callLater(0, d.errback, AuthenticationError("wrong auth")) else: if success == 0: reactor.callLater(0, d.callback, "Mario") else: reactor.callLater(0, d.errback, FourOhFourError("Not found")) return d def not_found(failure, retry, success): failure.trap(FourOhFourError) # this is superfluous here print failure.getErrorMessage() if retry == 0: raise AuthenticationError("Max retries") # do stuff print "retring..." d = defer.Deferred() d.addCallback(logon, success-1) reactor.callLater(1, d.callback, retry-1) # not really clean here return d def wrong_auth(failure): failure.trap(AuthenticationError) # this is superfluous here # do stuff print "something goes wrong" print failure.getErrorMessage() def loggedIn(user): print "hello %s" % user def stop(_): reactor.stop() d = logon(*map(int, sys.argv[1:])) d.addCallbacks(loggedIn, wrong_auth) d.addBoth(stop) reactor.run() </code></pre> <p>Invoke the code with three parameters: the maximum number of retries, at which retry the system should login the user and the third is a boolean indicating the correctness of the user credentials. Try the following invocations: <code>0 0 1</code>, <code>3 2 0</code>, <code>3 4 0</code>.</p> <p>I hope this example is more explicative.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload