[Twisted-Python] AFactory
Zooko
zooko at zooko.com
Tue Jul 23 23:24:41 MDT 2002
Folks:
In writing my Gnutella for Twisted implementation, which I have named "Zoot",
I encountered what seems to be a bit of a weakness in the current "Factory"
API. This occurred when I wanted each protocol instance to have a reference to
my Zoot object (the Zoot object contains the Gnutella logic for such operations
as routing a message from one connection to another).
The way to do this is to make a subclass of Factory, which I called
ZootFactory. ZootFactory gets a reference to the Zoot object when it
(ZootFactory) is constructed. Then ZootFactory's `buildProtocol()' method
looks like this:
class ZootFactory(Factory):
def __init__(self, zoot):
Factory.__init__(self)
self.zoot = zoot
def buildProtocol(self, addr):
p = Factory.buildProtocol(self, addr)
p.zoot = self.zoot
return p
It occurred to me that this idiom is probably useful to other developers of
applications on top of Twisted, and it is trivial to generalize it. I defined
class AFactory, like this:
class AFactory(Factory):
def __init__(self, protocol, application=None):
self.protocol = protocol
self.application = application
def buildProtocol(self, addr):
p = Factory.buildProtocol(self, addr)
p.application = self.application
return p
You can see it through viewcvs at:
http://twistedmatrix.com/users/jh.twistd/viewcvs/cgi/viewcvs.cgi/twisted/zoot/AFactory.py?rev=HEAD&content-type=text/vnd.viewcvs-markup&cvsroot=Twisted
My `updateApplication()' function in zoottap.py is now reduced to a nice
simple:
def updateApplication(app, config):
f = AFactory(GnutellaTalker, Zoot())
app.listenTCP(int(config["port"]), f)
I suggest that twisted.internet.protocol.Factory should be changed to do what
AFactory does, making it so that my `updateApplication()' could use the
standard Factory instead of AFactory. I think it would be a
backward-compatible change to Factory which doesn't require other users of
Factory to change.
Regards,
Zooko
http://zooko.com/
More information about the Twisted-Python
mailing list