Wednesday, October 7, 2009

Twisted Sevices

Twisted is one of the more mature Python networking libraries in existence. It has been around for over half a decade and has a very feature-rich code-base. There are several sever types that can be implemented with Twisted. This is actually a real requirement for many applications. For instance, an web application will obviously need an HTTP server for the web front-end. That same application may also want to provide a lower-level server for an API that generates less overhead. However, having to write something custom just to ensure that these servers are started along with the application seems a bit much. Especially if the servers are both a Twisted implementation. Luckily, Twisted has just the solution for this scenario.

Twisted provides developers with a MultiService class that is used to create multiple network service that behave logically as one server. Server implementations in Twisted can set the parent service to be an instance of MultiService. This MultiService instance can then be started with multiple child servers.

However, one last step should be taken. In order to make your service work with the twistd command, that is make it a sub-command, you must make the service properly. This is done by implementing a class that implements the IServiceMaker interface. This same class should also implement the IPlugin interface since it is a Twisted plugin in addition to a service.

The IServiceMaker interface requires attributes that dictate the name of the sub-command used with twistd. Also, command parameters and a description are part of the interface and should be provided.

This is a really nice way for an application to manage multiple services provided by the same application. It also goes to show that Twisted's experience is also reflected in the API.