try: from mod_python import apache, util except ImportError: from dummy import apache, util import py __version__ = '0.1 unreleased' class handler_decorator(object): """base class for handler decorators""" def __call__(self, handler): def wrapper(request): return self.handler(handler, request) return wrapper class preparesite(handler_decorator): """sets some vars on request""" def handler(self, orghandler, request): request.form = util.FieldStorage(request) request.headers_out['X-Application'] = 'mod_deco v%s' % __version__ return orghandler(request) class responsewriter(handler_decorator): def handler(self, orghandler, request): try: ret = orghandler(request) except: exc, e, tb = py.std.sys.exc_info() self.handle_error(request, exc, e, tb) else: if type(ret) == int: # we assume the response has already been written... return ret if isinstance(ret, unicode): import re charset = 'UTF-8' match = re.match('charset=.*?;', request.content_type) if match: charset = match.group(1) ret = ret.encode(charset) elif not isinstance(ret, str): ret = str(ret) request.headers_out['Content-Length'] = str(len(ret)) request.write(ret) return apache.OK def handle_error(self, request, exc, e, tb): request.content_type = 'text/plain' request.status = apache.HTTP_INTERNAL_SERVER_ERROR request.write('\n'.join([ 'An exception occurred while handling your request:\n', '%s - %s' % (exc, e), ] + py.std.traceback.format_tb(tb))) apache.log_error('%s - %s' % (exc, e), apache.APLOG_ERR) del tb