Asyncore and Generators

November 30, 2001 | Fredrik Lundh

I’ve been playing with asyncore and 2.2’s new generator model. Here’s the idea:

Instead of passing events to callbacks, pass information to a single handle function (a generator) via instance attributes. When the handler needs more data from the network, use yield to pass control back to the asyncore dispatcher.

Does it work? You bet.

from YieldAsyncore import *

class httpClient(YieldDispatcherWithSend):

    def __init__(self, host, port, path): = host
        self.path = path
        YieldDispatcherWithSend.__init__(self, host, port)

    def handle(self):

        # send request
            "GET %s HTTP/1.0\r\nHost: %s\r\n\r\n" % (self.path,
        yield OK

        # look for response header
                i = string.index(, "\r\n\r\n")
            except ValueError:
                yield MORE # need more data
                print self, repr([:i])
                if not
                    yield OK

        # process response body
            print self, len(
            yield OK

        print self, "done"

It’s not co-routines, but it’s pretty damn close!

(In case it’s not obvious, the trick here is that you can create any number of httpClient instances, and let them all run in parallel.)


A Django site. rendered by a django application. hosted by webfaction.