Thursday, April 26, 2007

Fix indentation in VIM

Often times, i get which has the indentation completely messed up, not just mixing tab/spaces, but really "whack"

these commands seem to magically fix for at least 2 test cases:

:set filetype=xml
:filetype indent on
:e
gg=G

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)

Tuesday, April 24, 2007

Install run, and benchmark mod_wsgi in < 10 minutes

svn checkout http://modwsgi.googlecode.com/svn/trunk/ modwsgi
cd mod_wsgi
./configure
make
sudo make install
# note where mod_wsgi.so went on your system
echo "LoadModule wsgi_module /path/to/mod_wsgi.so" >> /path/to/apache2.conf

mkdir /var/www/wsgitest/
cd /var/www/wsgitest/

vi .htaccess
# [in .htaccess]
Options +ExecCGI
< Files hi.py >
SetHandler wsgi-script
</Files>
# [ end .htaccess]

vi hi.py
# [in hi.py]

#!/usr/bin/python

import web

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/html')
print "bye %s" % who

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

application = web.wsgifunc(web.webpyfunc(urls, globals()))

#[end hi.py ]


you can then browse to
http://localhost/wsgitest/hi.py/hi/there
# see "hello there"
http://localhost/wsgitest/hi.py/bye/bye%20bye
# see "bye bye bye"



(meaningless) Benchmarking:
change last line in hi.py to:
if __name__ == "__main__": web.run(urls,globals())
and save as cgi.py

cgi
$ ab -n 1000 -c 30 http://localhost/wsgitest/cgi.py/hi/there | grep 'Requests per second'

Requests per second: 4.08 [#/sec] (mean)

wsgi
$ ab -n 1000 -c 30 http://localhost/wsgitest/hi.py/hi/there | grep 'Requests per second'

Requests per second: 351.05 [#/sec] (mean)