[Twisted-Python] help w/simple echo example w/deferred and threads

exarkun at divmod.com exarkun at divmod.com
Fri Apr 2 16:49:53 EST 2004

On Fri, 02 Apr 2004 16:11:16 -0500, "john nielsen" <jn at who.net> wrote:
>I am trying to make a very simple echo server use threads to understand how twisted handles blocking code.  I think I have the server ok but I am not sure how to have the client grab the data from a thread that finished some time later. If I comment out the sleep call, everything works fine. I looked at deferred but am a little confused. What is the simple code the client missing?
> Thanks for any help,
> john
> Here is the server
> ###############
> from twisted.spread import pb
> from twisted.internet import reactor
> from twisted.python import threadable
> threadable.init()
> import time,random
> class t:
>     def __init__(self):
>         self.result=''
>     def test(self,st='same'):
>         time.sleep(1)
>         print 'done sleeping'
>         self.result=st+':'+str(time.time())
> class Echoer(pb.Root):
>     def __init__(self):
>         self.a=t()
>     def remote_echo(self, st):
>             reactor.callInThread(self.a.test,st)
>             print 'from thread',self.a.result
>             return self.a.result

  Instead of the above:

    class t:
        def test(self, st='same'):
            return st + ':' + str(time.time())

    from twisted.internet import threads

    class Echoer(pb.Root):
        def __init__(self):
            self.a = t()

        def remote_echo(self, st):
            return threads.deferToThread(self.a.test, st)

  This is a good example if "time.sleep(1)" is only a hand-wave put in place of real, computational-expensive code, which I assume it is.  If you simply want to delay the
result for one section, threads are not necessary:

        from twisted.internet import defer

        def remote_echo(self, st):
            d = defer.Deferred()
            reactor.callLater(1, d.callback, st + ':' + str(time.time() + 1))
            return d

  Be sure to read the Deferred howto in the documentation section of the website.


More information about the Twisted-Python mailing list