Twisted Python (07 Feb 2003)

Twisted describes itself as "Twisted is a framework, written in Python, for writing networked applications". You can browse the documentation to your hearts' delight, but I'll take you through the (small) code for doing a POP3 server.

class POP3(LineReceiver):
	def connectionMake (self):
		self.transport.write ("+OK POP3 Ready\r\n");
	def lineReceived(self, line):

factory = Factory ()
factory.protocol = POP3

reactor.listenTCP (8007, factory) ()

And that's all (minus the import lines). Since POP3 is purely a line based protocol we can subclass the LineReceiver which handles all the buffering for us. The code is pretty self explanatory.

Twisted works as an async core and, as such, your functions cannot block (say, reading a large mbox). In these cases, you use Twisted's threading functions:

	def command_RETR (self, parts):
		reactor.callInThread (self.RETR_worker, n, -1)
	def RETR_worker (self, n, top_lines):
		ret = cStringIO.StringIO ()
		n = self.mbox.message_numbers_get (n)

Twisted also offers very nice objects for callbacks when a thread function returns a value.

Twisted provides pretty much everything you could ask for in a networking framework and more besides. Just look at the list of modules in the API reference