[Twisted-Python] Simplifying my StatusMonitor

Brad Bollenbach brad at bbnet.ca
Thu Jul 17 16:30:15 EDT 2003


Okay, in the usual XP fashion, I'm doing a spike to assess two use cases
for Twisted:

1. Writing a simple monitor that checks the status of a response, to see
what it's like to write a foobar in Twisted.

2. How to schedule multiple monitor batches so they can run and report
back to a "central command" (maybe CentralCommand or something), which
can then determine whether or not (and to whom) an error report should
be sent. (I've scrapped the idea of a "monicron")

I did #1 this morning. It's 49 lines of Python, in what would have
otherwise been less than five of "normal", blocking code:

==== begin code ====


from twisted.web import client

class HTTPPageStatusGetter(client.HTTPPageGetter):
    """A getter that tells clients the status of a response"""
    def handleStatus(self, version, status, message):
        client.HTTPPageGetter.handleStatus(self, version, status, message)

class StatusMonitorFactory(client.HTTPClientFactory):
    """An HTTP Monitor that does something interesting with the
    HTTP status returned."""

    protocol = HTTPPageStatusGetter

    def page(self, page):

    def noPage(self, reason):
    def status(self, status):
        if self.waiting:
            self.waiting = 0
class StatusMonitor:
    def checkFor200OK(self, url):
        host, port, url = client._parse(url)
        factory = StatusMonitorFactory(host, url)
        reactor.connectTCP(host, port, factory)
        factory.deferred.addCallback(self.gotStatus, url)
        factory.deferred.addErrback(self.reportError, url)
        return factory.deferred

    def gotStatus(self, status, url):
        print "hooray, got status %s" % status

    def reportError(self, failure, url):
        print ":( There was a problem in %s" % url
        print failure

from twisted.internet import reactor

d = StatusMonitor().checkFor200OK('http://www.bbnet.ca/')
d.addCallback(lambda *a: reactor.stop())

==== end code ====

How could I have made this simpler? What approach would you have taken
to solve this problem?

Brad Bollenbach

More information about the Twisted-Python mailing list