defer_alreadycallederror.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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 pprint import pprint
  5. def getData(inputData):
  6. print('getData({0})'.format(inputData))
  7. deferred = defer.Deferred()
  8. # simulate a delayed result by asking reactor
  9. # to fire in 2 seconds with inputData * 3 as result
  10. print("return result (x*3) in 2 sec...")
  11. print(deferred)
  12. reactor.callLater(2, deferred.callback, inputData * 3)
  13. print(deferred)
  14. reactor.callLater(3, deferred.callback, inputData * 3)
  15. print(deferred)
  16. return deferred
  17. def cbPrint(result):
  18. print("cbPrint({0})".format(result))
  19. # doing eferred, or the return result + 1 works
  20. print("return result (x+1) in 1 sec...")
  21. deferred = defer.Deferred()
  22. reactor.callLater(1, deferred.callback, result + 1)
  23. return deferred
  24. # return result + 1
  25. def cbPrint2(result):
  26. print("cbPrint2({0})".format(result))
  27. print("return result (x+2) ...")
  28. # print("(this isn't a defer)") # it is now! :P
  29. # return a Deferred object already called back with the value of result
  30. return defer.succeed(result + 2)
  31. # return result + 2
  32. d = getData(3)
  33. # Ok, chaining callbacks is ... different.
  34. d.addCallback(cbPrint)
  35. # Before return result, this was printing None.
  36. d.addCallback(cbPrint2)
  37. d.addCallback(cbPrint)
  38. d.addCallback(print)
  39. print("Stop the reactor in 7 seconds...")
  40. reactor.callLater(7, reactor.stop)
  41. print("starting the reactor")
  42. reactor.run()
  43. print("Reactor has been safely shutdown. :P")