WSGI – using a decorator for sensing a stand alone server, CGI or WSGI app handler

Python’s WSGI Framework makes writing powerful applications easy.

But there is one thing that always drives me CRAZY.  I always have to write a either

setup a WSGI Handler Framework / like mod_wsgi or use some other wrapper to host the “application progress.”

after looking around at solutions I found a site with a very clever solution.

Using a decorator to determine how the application function is being called.

the first part of the magic came from

http://hackmap.blogspot.com/2008/04/python-script-as-wsgi-cgi-or-standalone.html

where the author suggested using a decorator to wrap the “WSGI APPLICATION  function”

@wrapplication(3000)

def application(environ, start_response):

start_response(“200 OK”, [(‘Content-Type’, ‘text/plain’)])
yield “How do you like the teaches of peaches?\n”
yield “from ” + environ[‘hello’]

— a very clever approach – so I took the handler functions and put them into a python script of its own.

this allows for loading the decorator in a simple “From – Import line”

—————–

from wrapplication import wrapplication

—————–

so that no matter how I want to run the application function – it will all just work – no changes required!

all you have to do is use this decorator (change your port number here)
@wrapplication(3000)

def application(environ, start_response):

————–

to do this yourself – this is your wrapplication.py file

#!/usr/bin/python
import os

class EMiddle(object):
def __init__(self, app):
self.app = app
def __call__(self, env, start_response):
env['hello'] = 'wsgi'
return self.app(env, start_response)

def wrapplication(port):
def wrapper(wsgi_app):
if 'TERM' in os.environ:
print "serving on port: %i" % port
os.environ['hello'] = 'standalone'
from wsgiref.simple_server import make_server
make_server('', port, wsgi_app).serve_forever()

elif 'CGI' in os.environ.get('GATEWAY_INTERFACE',''):
os.environ['hello'] = 'cgi'
import wsgiref.handlers
wsgiref.handlers.CGIHandler().run(wsgi_app)
else:
return EMiddle(wsgi_app)
return wrapper

'''
@wrapplication(3000)
def application(environ, start_response):
start_response("200 OK", [('Content-Type', 'text/plain')])
yield "How do you like the teaches of peaches?\n"
yield "from " + environ['hello']
'''

Leave a comment