[Twisted-Python] Example of re-usable ClientFactories?
Orestis Markou
orestis at orestis.gr
Wed Jun 15 13:03:14 EDT 2011
Hello,
I've gotten to the point in my tutorial that I'm giving out examples of writing clients. Example:
class HTTPGETProtocol(protocol.Protocol):
def connectionMade(self):
self.buffer = []
self.transport.write('GET %s HTTP/1.0\r\n' % self.factory.path)
self.transport.write('User-Agent: europython/2011\r\n')
self.transport.write('\r\n')
def dataReceived(self, data):
self.buffer.append(data)
def connectionLost(self, reason):
self.factory.deferred.callback(''.join(self.buffer))
def get(host, path):
f = protocol.ClientFactory()
f.protocol = HTTPGETProtocol
f.path = path
f.deferred = defer.Deferred()
reactor.connectTCP(host, 80, f)
return f.deferred
So far as I can tell, this is a common idiom (albeit with a ClientFactory subclass) - create a single-use factory, store some instance variables into it, connect somewhere, let the protocol do its thing by accessing the factory's instance variables. Of course, real-world examples are much more complex, but the pattern remains pretty much the same.
I'm curious, is there any case where a ClientFactory.buildProtocol would be used more than once? The only case I can think is something like ReconnectingClientFactory that will need to re-initiate the connection, but it doesn't even use that kind of functionality.
Thinking more about it, a factory could be reused by connecting it to different addresses, so it would coordinate different protocols.
But, for most of the one-shot cases it seems that a ClientCreator (or an endpoint) would serve the same purpose, no?
Any pointers would be appreciated.
Orestis
More information about the Twisted-Python
mailing list