Howto Deferred
Jean-Paul Calderone
calderone.jeanpaul at gmail.com
Thu Jul 14 08:21:00 EDT 2011
On Jul 14, 3:07 am, marco <ma... at minasithil.org> wrote:
> Hello gals and guys,
>
> I'm an experienced Python user and I'd like to begin playing with
> Twisted.
> I started RTFM the tutorial advised on the official site and I found it
> really useful and well done.
>
> Now I'd like to practice a bit by coding a little program that reads
> strings from a serial device and redirects them remotely via TCP. For
> that sake I'm trying to use deferred.
>
Deferreds probably aren't a good solution for this problem. They're
useful
for one-time events, but you have an event that repeats over and over
again
with different data.
> In the tutorial, a deferred class is instantiated at factory level, then
> used and destroyed.
>
> And here things get harder for me.
> Now, in my test program I need to manage data which comes in a "random"
> manner, and I thought about doing it in a few possible ways:
>
> 1. create a deferred at factory level and every time I read something
> from the serial port add some callbacks:
>
> class SerToTcpProtocol(Protocol):
>
> def dataReceived(self, data):
> # deferred is already instantiated and launched
> # self.factory.sendToTcp sends data to the TCP client
> self.factory.deferred.addCallback(self.factory.sendToTcp, data)
>
Or you could do self.factory.sendToTcp(data)
> 2. or, either, create a deferred at protocol level every time I receive
> something, then let the deferred do what I need and destroy it:
>
> class SerToTcpProtocol(Protocol):
>
> def dataReceived(self, data):
> d = defer.Deferred()
> d.addCallback(self.factory.sendToTcp, data)
> d.callback(data)
>
Same here. :)
> 3. or again, use a deferred list:
>
> class SerToTcpProtocol(Protocol):
>
> def dataReceived(self, data):
> d = defer.Deferred()
> d.addCallback(self.factory.sendToTcp, data)
> self.factory.listDeferred.addCallback(lambda d)
> d.callback(data)
>
I'm not sure what the listDeferred is there for.
Deferreds are a good abstraction for "do one thing and then tell
me what the result was". You have a different sort of thing here,
where there isn't much of a result (sending to tcp probably always
works until you lose your connection). A method call works well
for that.
Jean-Paul
More information about the Python-list
mailing list