Adding a Simple Web Interface14 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 = """ <html><head>Status </head><body>%s </body></html>""" % status 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='0.0.0.0') httpd.serve_forever() WebServer().start() while 1: time.sleep(2) status = random() print "Status is now",status
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