[Twisted-Python] async code structure question

snacktime snacktime at gmail.com
Thu Feb 10 14:26:11 EST 2005

> Do() should return a Deferred that has result when processing is done,
> and then you can Do().addCallback(lambda: self.transport.write("hello"))
> or something.
> e.g.
> def Do():
>    d = deferToThread(foo)
>    d.addCallback(processResult)
>    return d
> or
> def Do():
>    # processing in this case is waiting for one second
>    d = Deferred()
>    reactor.callLater(d.callback, 1)
>    return d

Thanks Itamar.  I think I understand these examples to a point, but
what I don't understand is how to implement it when you are calling
methods several levels deep into other classes.  For example the
method authorize() in class Authorization below is where the final
data is that I need to print back to the client via Printdata in the
protocol handler.  In authorize there are several chained deferreds
also, and the last one needs to somehow trigger the very first
callback that was added in dataReceived().

Specifically what I am having the most difficulty with is this.  In
Do() is where the Deferred is created that needs to have it's
callbacks fired.  How can I fire off that callback from authorize()
and have authorize() pass it the final data?

class OT(Protocol):
    def dataReceived(self, data):
    def Do():
      d = defer.Deferred()
      c = ProcessTransaction()
      reactor.callLater(0, c.Do,data)

    def PrintData(self,data):
        self.transport.write("%s\r\n" % data)

class ProcessTransaction:

  def Do(self,data):
    ''' Do some sanity checks on data and see what network to process
the transaction through'''
    if network == 'vital':
      d = Vital()
       response = d.Submit()

class Vital:
  ''' Run method based on the transaction type '''

   if transaction_type == 'AUTHORIZE':
      r = Authorization(req)
      response = r.Submit()

class Authorization:

  def authorize(self):
    ''' Here we have several chained deferreds to handle some database
    submit the transaction via a post, and finally format a final
response which needs to be printed to the client.

More information about the Twisted-Python mailing list