Adding a Simple Web Interface

14 June 2008 10:53

I had the idea to do this this morning. It is satisfyingly simple, and I spent about half my time trying to fix the bug caused by calling the thread's run() method instead of its start() method.

This is exactly the sort of thing paste was designed for: by making the web server into a well-designed library, it's really easy to use it whenever you need to. I've recently realised how much more powerful libraries are than frameworks, and this is a good example.

from paste.urlmap import URLMap
from paste.cascade import Cascade
from paste.urlparser import StaticURLParser
from paste.httpserver import serve
import time
import threading
from random import random

status = [random()]

def index(environ, start_response):
    start_response('200 OK', [('Content-type','text/html')])
    data = """
    </body></html>""" % status[0]
    return [data]

class WebServer(threading.Thread):
    def run(self):
        # Set up the URL map for the app
        app = URLMap()
        app['/'] = index

        httpd = serve(app, port=8003, host='')


while 1:
    status[0] = random()
    print "Status is now",status[0]

Note that the shared data object between threads needs to be mutable for obvious reasons, so in this case I just wrap the float in a list.

Leave a comment