from repoze.profile.profiler import AccumulatingProfileMiddleware class OptionalProfileMiddleware(AccumulatingProfileMiddleware): # Inherits __init__(). def __call__(self, environ, start_response): def do_cookie(val): start_response("302 Found", [('Location', environ.get('SCRIPT_NAME', '/')), ('Set-Cookie', 'profile=' + val)]) path_info = environ.get('PATH_INFO') if path_info == self.path + '_on': do_cookie('on') return () elif path_info == self.path + '_off': do_cookie('off') return () elif ('profile=on' in environ.get('HTTP_COOKIE', '') or path_info == self.path): try: return AccumulatingProfileMiddleware.__call__(self, environ, start_response) except EOFError: start_response("200 OK", [('Content-Type', 'text/plain')]) return ("No profile data found; hit up profile_on to enable profiling of your requests.",) else: return self.app(environ, start_response)