Wednesday, April 25, 2007

Using Python MiddleWare

just trying to figure this stuff out. it's pretty simple, but there's one level of abstraction through web.py. you can use middleware to add keys to the environ for example.
http://groovie.org/files/WSGI_Presentation.pdf


#!/usr/bin/python

import web
import random

class hi(object):
def GET(self,who='world'):
web.header('Content-type','text/html')
print "hello %s" % who

class bye(object):
def GET(self,who='world'):
web.header('Content-type','text/plain')
print "bye %s" % who

for c in web.ctx.env:
print c, web.ctx.env[c]

class other(object):
def GET(self):
web.header('Content-type','text/plain')
for c in web.ctx:
print c, web.ctx[c]

urls = ( '/bye/(.*)', 'bye'
,'/hi/(.*)' , 'hi'
, '/.*' , 'other')

class RandomWare(object):
def __init__(self, app):
self.your_app = app;

def __call__(self,environ,start):
environ['hello'] = random.random()
return self.your_app(environ,start)

def random_mw(app):
return RandomWare(app)

if __name__ == "__main__":

web.run(urls,globals(),random_mw)

No comments: