Wednesday, February 13, 2008

Simple Python Web Server

Corey Goldberg blogged about making simple web interfaces. I was going to comment with another example of a simple web server, but his blog kept spitting back errors, so I'll post it here instead.

Corey's code was based on BaseHTTPServer, here's another way to do this (as a Twisted tac file):

from twisted.web import server, resource
from twisted.application import internet, service

class Foo(resource.Resource):
def render(self, request):
return "hello world"

root = resource.Resource()
root.putChild("foo", Foo())

application = service.Application("Tiny Web")
internet.TCPServer(8080, server.Site(root)).setServiceParent(application)

Of course, it requires a bit more than just the standard library. ;) This has a couple extra nice features though - it does logging, for example, and it can be trivially daemonized, or run under the profiler or the debugger, or chrooted or as a different uid/gid. Plus the Foo resource can easily be relocated into a "real" program, since it is entirely distinct from the HTTP server part of the code.

There's an even simpler way to express this though, as an rpy instead of a tac:

from twisted.web.resource import Resource

class Foo(Resource):
def render(self, request):
return "hello world"

resource = Foo()

Just drop this into a directory and run a Twisted web server pointed at it (eg, twistd web --processor rpy=twisted.web.script.ResourceScript --path bar/). You can even change the code without restarting the server if you do it this way. rpys can be convenient for one-off hacks, but clearly it's not suitable for anything larger scale than that.

No comments: