[Stackless] Simple Server Example On second thought...Twisted + Stackless?

Andrew Francis andrewfr_ice at yahoo.com
Fri Nov 17 02:40:08 CET 2006

Hello Kuros:

>I have most of the framework already written, so I'm
>talking about rewriting it with stackless in my
previous >message. I use twisted for the networking
core on what >I've done so far...is it possible for me
to leave that 
>part alone and integrate stackless somehow?

I would have to look at your code to determine this.
However here is a simple example of how to use Twisted
with Stackless. The server is based on
requestHandler.py on page 41 of the "Twisted Network
Programming Essentials" book. The trick is to have the
Twisted request handlers and tasklets share a channel.

When I have time, I will put this on the Wiki. 

Simulate Cgi scripts
example of using Twisted with Stackless Python

The request handler simply echos back the CGI path and
the number of times the cgi script tasklet is called

#!/usr/bin/env python
import stackless
from twisted.web           import http

The server tasklet
class Server(object):
    def execute(self, port, scripts):
        give the handler a dictionary of <path,
        MyRequestHandler.scripts = scripts
        reactor.listenTCP(port, MyHttpFactory())

cgi script
class Cgi(object):
    def __init__(self, name, channel):
        self.name = name
        self.channel = channel
        self.count = 0

    def execute(self):
        while (1):
            path = self.channel.receive()
            print path
            self.channel.send("<html><body>" + \
                               str(self.name) + "
received path: " + path + "count :" + str(self.count)
+ \
            self.count = self.count + 1

class MyRequestHandler(http.Request):
    scripts = None
    def process(self):
        # look up the channel of the cgiScript
associated with path
        # receive the output
        result = self.scripts[self.path].receive()
        # write back to the http agent
class MyHttp(http.HTTPChannel):
    requestFactory = MyRequestHandler
class MyHttpFactory(http.HTTPFactory):
    protocol = MyHttp
if __name__ == "__main__":
    from twisted.internet import reactor
    cgiScripts = {}
    let us generate some cgiScript tasklets
    for s in range(0,100):
        path = "/" + str(s)
        channel = stackless.channel()
        cgiScripts[path] = channel
        cgiTasklet = Cgi(s, channel)
    start the server
    server = Server()
    while (stackless.getruncount() > 1):

Sponsored Link

Mortgage rates near 39yr lows. 
$510k for $1,698/mo. Calculate new payment! 

Stackless mailing list
Stackless at stackless.com

More information about the Stackless mailing list