defer_errback.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #!/usr/bin/env python
  2. # https://twistedmatrix.com/documents/16.2.0/core/howto/defer.html
  3. from twisted.internet import reactor, defer
  4. from twisted.python.failure import Failure
  5. from pprint import pprint
  6. def getData(inputData):
  7. print('getData({0})'.format(inputData))
  8. deferred = defer.Deferred()
  9. # simulate a delayed result by asking reactor
  10. # to fire in 2 seconds with inputData * 3 as result
  11. print("return result in 1 sec...")
  12. reactor.callLater(1, deferred.callback, inputData+1)
  13. return deferred
  14. def cbPrint(result):
  15. print("cbPrint({0})".format(result))
  16. # doing eferred, or the return result + 1 works
  17. print("return result (x+1) in 1 sec...")
  18. deferred = defer.Deferred()
  19. if result % 2 == 0:
  20. reactor.callLater(1, deferred.callback, result + 1)
  21. else:
  22. reactor.callLater(2, deferred.errback, ValueError("You used an odd number!"))
  23. return deferred
  24. # return result + 1
  25. def ePrint(result):
  26. """ Errback message received here.
  27. However, I get little to no control over this.
  28. I don't get anything (other then the error itself),
  29. so I can't do much with the deferred.
  30. I'm not sure how this is useful.
  31. """
  32. print("ERROR:", result)
  33. # return twisted.python.failure.Failure
  34. # return Failure
  35. # return ValueError("Errback handlying sucks...")
  36. d = getData(1)
  37. # Ok, chaining callbacks is ... different.
  38. d.addCallback(cbPrint)
  39. # d.addErrback(ePrint)
  40. d.addCallback(cbPrint)
  41. # d.addErrback(ePrint)
  42. d.addCallback(cbPrint)
  43. # d.addErrback(ePrint)
  44. d.addCallback(cbPrint)
  45. d.addErrback(ePrint)
  46. print("Stop the reactor in 15 seconds...")
  47. reactor.callLater(15, reactor.stop)
  48. print("starting the reactor")
  49. reactor.run()
  50. print("Reactor has been safely shutdown. :P")