Managing Multiple Services

One of the most powerful features of Twisted is its ability to run multiple services in a single process. You can write an application that shares objects and data with many different protocols at the same time. You can also manage the different services in an application at runtime, starting and stopping them individually without having to restart your application.

11.3.1. How Do I Do That?

Add more than one service to an application object and run the application using twistd. You can iterate through the current services in your application by wrapping the application object in the service.IServiceCollection interface. Call startService and stopService to start or stop one of the services. Example 11-4 creates an application that offers both web and Telnet interfaces to the same data, and a web administration interface that lets you selectively start and stop services.

Example 11-4. multiservice.py

from twisted.application import service, internet from twisted.internet import protocol, reactor, defer from twisted.protocols import basic from twisted.web import resource, server as webserver class Reverser: def _ _init_ _(self): self.history = [] def reverse(self, string): self.history.append(string) reversed = string[::-1] return reversed class ReverserLineProtocol(basic.LineReceiver): def lineReceived(self, line): if hasattr(self, 'handle_' + line): getattr(self, 'handle_' + line)( ) else: self.sendLine(self.factory.reverser.reverse(line)) def handle_quit(self): self.transport.loseConnection( ) class ReverserLineFactory(protocol.ServerFactory): protocol = ReverserLineProtocol def _ _init_ _(self, reverser): self.reverser = reverser class ReverserPage(resource.Resource): def _ _init_ _(self, reverser): self.reverser = reverser def render(self, request): if request.args.has_key("string"): string = request.args["string"][0] reversed = self.reverser.reverse(string) else: reversed = "" return """

Previous Strings

""" % (reversed, " ".join(["