WebError-0.10.3+dfsg/0000775000000000000000000000000011466345335012753 5ustar rootrootWebError-0.10.3+dfsg/weberror/0000775000000000000000000000000011466345335014602 5ustar rootrootWebError-0.10.3+dfsg/weberror/errormiddleware.py0000664000000000000000000004335011335430006020331 0ustar rootroot# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org) # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php """ Error handler middleware """ import sys import traceback import cgi try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from weberror import formatter, collector, reporter from paste import wsgilib from paste import request from paste.util import import_string import types __all__ = ['ErrorMiddleware', 'handle_exception'] class _NoDefault(object): def __repr__(self): return '' NoDefault = _NoDefault() class ErrorMiddleware(object): """ Error handling middleware Usage:: error_catching_wsgi_app = ErrorMiddleware(wsgi_app) Settings: ``debug``: If true, then tracebacks will be shown in the browser. ``error_email``: an email address (or list of addresses) to send exception reports to ``error_log``: a filename to append tracebacks to ``show_exceptions_in_wsgi_errors``: If true, then errors will be printed to ``wsgi.errors`` (frequently a server error log, or stderr). ``from_address``, ``smtp_server``, ``error_subject_prefix``, ``smtp_username``, ``smtp_password``, ``smtp_use_tls``: variables to control the emailed exception reports ``error_message``: When debug mode is off, the error message to show to users. ``xmlhttp_key``: When this key (default ``_``) is in the request GET variables (not POST!), expect that this is an XMLHttpRequest, and the response should be more minimal; it should not be a complete HTML page. Environment Configuration: ``paste.throw_errors``: If this setting in the request environment is true, then this middleware is disabled. This can be useful in a testing situation where you don't want errors to be caught and transformed. ``paste.expected_exceptions``: When this middleware encounters an exception listed in this environment variable and when the ``start_response`` has not yet occurred, the exception will be re-raised instead of being caught. This should generally be set by middleware that may (but probably shouldn't be) installed above this middleware, and wants to get certain exceptions. Exceptions raised after ``start_response`` have been called are always caught since by definition they are no longer expected. """ def __init__(self, application, global_conf=None, debug=NoDefault, error_email=None, error_log=None, show_exceptions_in_wsgi_errors=NoDefault, from_address=None, smtp_server=None, smtp_username=None, smtp_password=None, smtp_use_tls=False, error_subject_prefix=None, error_message=None, xmlhttp_key=None, reporters=None): from paste.util import converters self.application = application # @@: global_conf should be handled elsewhere in a separate # function for the entry point if global_conf is None: global_conf = {} if debug is NoDefault: debug = converters.asbool(global_conf.get('debug')) if show_exceptions_in_wsgi_errors is NoDefault: show_exceptions_in_wsgi_errors = converters.asbool(global_conf.get('show_exceptions_in_wsgi_errors')) self.debug_mode = converters.asbool(debug) if error_email is None: error_email = (global_conf.get('error_email') or global_conf.get('admin_email') or global_conf.get('webmaster_email') or global_conf.get('sysadmin_email')) self.error_email = converters.aslist(error_email) self.error_log = error_log self.show_exceptions_in_wsgi_errors = show_exceptions_in_wsgi_errors if from_address is None: from_address = global_conf.get('error_from_address') if from_address is None: if self.error_email: from_address = self.error_email[0] else: from_address = 'errors@localhost' self.from_address = from_address if smtp_server is None: smtp_server = global_conf.get('smtp_server', 'localhost') self.smtp_server = smtp_server self.smtp_username = smtp_username or global_conf.get('smtp_username') self.smtp_password = smtp_password or global_conf.get('smtp_password') self.smtp_use_tls = smtp_use_tls or converters.asbool(global_conf.get('smtp_use_tls')) self.error_subject_prefix = error_subject_prefix or '' if error_message is None: error_message = global_conf.get('error_message') self.error_message = error_message if xmlhttp_key is None: xmlhttp_key = global_conf.get('xmlhttp_key', '_') self.xmlhttp_key = xmlhttp_key reporters = reporters or global_conf.get('error_reporters') if reporters and isinstance(reporters, basestring): reporter_strings = reporters.split() reporters = [] for reporter_string in reporter_strings: reporter = import_string.eval_import(reporter_string) if isinstance(reporter, (type, types.ClassType)): reporter = reporter() reporters.append(reporter) self.reporters = reporters or [] def __call__(self, environ, start_response): """ The WSGI application interface. """ # We want to be careful about not sending headers twice, # and the content type that the app has committed to (if there # is an exception in the iterator body of the response) if environ.get('paste.throw_errors'): return self.application(environ, start_response) environ['paste.throw_errors'] = True try: __traceback_supplement__ = Supplement, self, environ sr_checker = ResponseStartChecker(start_response) app_iter = self.application(environ, sr_checker) return self.make_catching_iter(app_iter, environ, sr_checker) except: exc_info = sys.exc_info() try: start_response('500 Internal Server Error', [('content-type', 'text/html; charset=utf8')], exc_info) # @@: it would be nice to deal with bad content types here response = self.exception_handler(exc_info, environ) if isinstance(response, unicode): response = response.encode('utf8') return [response] finally: # clean up locals... exc_info = None def make_catching_iter(self, app_iter, environ, sr_checker): if isinstance(app_iter, (list, tuple)): # These don't raise return app_iter return CatchingIter(app_iter, environ, sr_checker, self) def exception_handler(self, exc_info, environ): simple_html_error = False if self.xmlhttp_key: get_vars = wsgilib.parse_querystring(environ) if dict(get_vars).get(self.xmlhttp_key): simple_html_error = True return handle_exception( exc_info, environ['wsgi.errors'], html=True, debug_mode=self.debug_mode, error_email=self.error_email, error_log=self.error_log, show_exceptions_in_wsgi_errors=self.show_exceptions_in_wsgi_errors, error_email_from=self.from_address, smtp_server=self.smtp_server, smtp_username=self.smtp_username, smtp_password=self.smtp_password, smtp_use_tls=self.smtp_use_tls, error_subject_prefix=self.error_subject_prefix, error_message=self.error_message, simple_html_error=simple_html_error, reporters=self.reporters) class ResponseStartChecker(object): def __init__(self, start_response): self.start_response = start_response self.response_started = False def __call__(self, *args): self.response_started = True self.start_response(*args) class CatchingIter(object): """ A wrapper around the application iterator that will catch exceptions raised by the a generator, or by the close method, and display or report as necessary. """ def __init__(self, app_iter, environ, start_checker, error_middleware): self.app_iterable = app_iter self.app_iterator = iter(app_iter) self.environ = environ self.start_checker = start_checker self.error_middleware = error_middleware self.closed = False def __iter__(self): return self def next(self): __traceback_supplement__ = ( Supplement, self.error_middleware, self.environ) if self.closed: raise StopIteration try: return self.app_iterator.next() except StopIteration: self.closed = True close_response = self._close() if close_response is not None: return close_response else: raise StopIteration except: self.closed = True close_response = self._close() exc_info = sys.exc_info() response = self.error_middleware.exception_handler( exc_info, self.environ) if close_response is not None: response += ( '
Error in .close():
%s' % close_response) if not self.start_checker.response_started: self.start_checker('500 Internal Server Error', [('content-type', 'text/html')], exc_info) return response def close(self): # This should at least print something to stderr if the # close method fails at this point if not self.closed: self._close() def _close(self): """Close and return any error message""" if not hasattr(self.app_iterable, 'close'): return None try: self.app_iterable.close() return None except: close_response = self.error_middleware.exception_handler( sys.exc_info(), self.environ) return close_response class Supplement(object): """This is a supplement used to display standard WSGI information in the traceback. Additional configuration information can be added under a Configuration section by populating the environ['weberror.config'] variable with a dictionary to include. """ def __init__(self, middleware, environ): self.middleware = middleware self.environ = environ self.source_url = request.construct_url(environ) def extraData(self): data = {} cgi_vars = data[('extra', 'CGI Variables')] = {} wsgi_vars = data[('extra', 'WSGI Variables')] = {} hide_vars = ['paste.config', 'wsgi.errors', 'wsgi.input', 'wsgi.multithread', 'wsgi.multiprocess', 'wsgi.run_once', 'wsgi.version', 'wsgi.url_scheme'] for name, value in self.environ.items(): if name.upper() == name: if value: cgi_vars[name] = value elif name not in hide_vars: wsgi_vars[name] = value if self.environ['wsgi.version'] != (1, 0): wsgi_vars['wsgi.version'] = self.environ['wsgi.version'] proc_desc = tuple([int(bool(self.environ[key])) for key in ('wsgi.multiprocess', 'wsgi.multithread', 'wsgi.run_once')]) wsgi_vars['wsgi process'] = self.process_combos[proc_desc] wsgi_vars['application'] = self.middleware.application if 'weberror.config' in self.environ: data[('extra', 'Configuration')] = dict(self.environ['weberror.config']) return data process_combos = { # multiprocess, multithread, run_once (0, 0, 0): 'Non-concurrent server', (0, 1, 0): 'Multithreaded', (1, 0, 0): 'Multiprocess', (1, 1, 0): 'Multi process AND threads (?)', (0, 0, 1): 'Non-concurrent CGI', (0, 1, 1): 'Multithread CGI (?)', (1, 0, 1): 'CGI', (1, 1, 1): 'Multi thread/process CGI (?)', } def handle_exception(exc_info, error_stream, html=True, debug_mode=False, error_email=None, error_log=None, show_exceptions_in_wsgi_errors=False, error_email_from='errors@localhost', smtp_server='localhost', smtp_username=None, smtp_password=None, smtp_use_tls=False, error_subject_prefix='', error_message=None, simple_html_error=False, reporters=None, ): """ For exception handling outside of a web context Use like:: import sys import paste import paste.error_middleware try: do stuff except: paste.error_middleware.exception_handler( sys.exc_info(), paste.CONFIG, sys.stderr, html=False) If you want to report, but not fully catch the exception, call ``raise`` after ``exception_handler``, which (when given no argument) will reraise the exception. """ reported = False exc_data = collector.collect_exception(*exc_info) extra_data = '' if error_email: rep = reporter.EmailReporter( to_addresses=error_email, from_address=error_email_from, smtp_server=smtp_server, smtp_username=smtp_username, smtp_password=smtp_password, smtp_use_tls=smtp_use_tls, subject_prefix=error_subject_prefix) rep_err = send_report(rep, exc_data, html=html) if rep_err: extra_data += rep_err else: reported = True if reporters: for rep in reporters: rep_err = send_report(rep, exc_data, html=html) if rep_err: extra_data += rep_err else: ## FIXME: should this be true? reported = True if error_log: rep = reporter.LogReporter( filename=error_log) rep_err = send_report(rep, exc_data, html=html) if rep_err: extra_data += rep_err else: reported = True if show_exceptions_in_wsgi_errors: rep = reporter.FileReporter( file=error_stream) rep_err = send_report(rep, exc_data, html=html) if rep_err: extra_data += rep_err else: reported = True else: error_stream.write('Error - %s: %s\n' % ( exc_data.exception_type, exc_data.exception_value)) if html: if debug_mode and simple_html_error: return_error = formatter.format_html( exc_data, include_hidden_frames=False, include_reusable=False, show_extra_data=False) reported = True elif debug_mode and not simple_html_error: error_html = formatter.format_html( exc_data, include_hidden_frames=True, include_reusable=False) head_html = '' return_error = error_template( head_html, error_html, extra_data) extra_data = '' reported = True else: msg = error_message or ''' An error occurred. See the error logs for more information. (Turn debug on to display exception reports here) ''' return_error = error_template('', msg, '') else: return_error = None if not reported and error_stream: err_report = formatter.format_text(exc_data, show_hidden_frames=True)[0] err_report += '\n' + '-'*60 + '\n' error_stream.write(err_report) if extra_data: error_stream.write(extra_data) return return_error def send_report(rep, exc_data, html=True): try: rep.report(exc_data) except: output = StringIO() traceback.print_exc(file=output) if html: return """

Additionally an error occurred while sending the %s report:

%s

""" % ( cgi.escape(str(rep)), output.getvalue()) else: return ( "Additionally an error occurred while sending the " "%s report:\n%s" % (str(rep), output.getvalue())) else: return '' def error_template(head_html, exception, extra): return ''' Server Error %s

Server Error

%s %s ''' % (head_html, exception, extra) def make_error_middleware(app, global_conf, **kw): return ErrorMiddleware(app, global_conf=global_conf, **kw) doc_lines = (ErrorMiddleware.__doc__ or '').splitlines(True) for i in range(len(doc_lines)): if doc_lines[i].strip().startswith('Settings'): make_error_middleware.__doc__ = ''.join(doc_lines[i:]) break del i, doc_lines WebError-0.10.3+dfsg/weberror/evalcontext.py0000664000000000000000000000364611003221406017474 0ustar rootrootfrom cStringIO import StringIO import traceback import threading import pdb import sys exec_lock = threading.Lock() class EvalContext(object): """ Class that represents a interactive interface. It has its own namespace. Use eval_context.exec_expr(expr) to run commands; the output of those commands is returned, as are print statements. This is essentially what doctest does, and is taken directly from doctest. """ def __init__(self, namespace, globs): self.namespace = namespace self.globs = globs def exec_expr(self, s): out = StringIO() exec_lock.acquire() save_stdout = sys.stdout try: debugger = _OutputRedirectingPdb(save_stdout) debugger.reset() pdb.set_trace = debugger.set_trace sys.stdout = out try: code = compile(s, '', "single", 0, 1) exec code in self.namespace, self.globs debugger.set_continue() except KeyboardInterrupt: raise except: traceback.print_exc(file=out) debugger.set_continue() finally: sys.stdout = save_stdout exec_lock.release() return out.getvalue() # From doctest class _OutputRedirectingPdb(pdb.Pdb): """ A specialized version of the python debugger that redirects stdout to a given stream when interacting with the user. Stdout is *not* redirected when traced code is executed. """ def __init__(self, out): self.__out = out pdb.Pdb.__init__(self) def trace_dispatch(self, *args): # Redirect stdout to the given stream. save_stdout = sys.stdout sys.stdout = self.__out # Call Pdb's trace dispatch method. try: return pdb.Pdb.trace_dispatch(self, *args) finally: sys.stdout = save_stdout WebError-0.10.3+dfsg/weberror/eval-media/0000775000000000000000000000000012415227316016577 5ustar rootrootWebError-0.10.3+dfsg/weberror/eval-media/traceback.css0000664000000000000000000002327511126232531021232 0ustar rootroot/* @override http://localhost:5000/_debug/media/traceback.css */ body{ margin: 0px; padding: 0px;/* 4% 0 0;*/ font-family: Verdana, Arial, sans-serif; font-size: 75%; line-height: 160%; color: #333; /*min-width:770px; max-width: 1100px;*/ } /* Layout Styles */ div#nav-bar{ border-top: 1px solid #fff; float: right; width: 100%; margin-top: 0px; } div#main-content{ float: left; width: 100%; background: #fff; } div#side-content{ padding-top: 42px; float: left; margin-top: 0px; width: 30%; clear: right; height: 550px; } div.three, div.two, div.one{ width: 746px; padding: 0 12px 0px 12px; clear: both; } div.three div.a, div.two div.a{ float: left; clear: left; width: 204px; } div.a div.padding, div.b div.padding, div.c div.padding, div.one div.padding{ padding: 0px 12px 20px 12px; } div.three div.b{ float: left; width: 271px; } div.three div.c{ float: left; clear: right; width: 271px; } div.two div.b{ float: left; clear: right; width: 542px; } div.frame { border-bottom: 1px solid #ccc; } /* Logo */ h1#logo{ margin: 20px 5% 0 5%; padding: 0; float: left; width: 155px; height: 52px; } /* Nav Bar */ #nav-global { margin:0; white-space:nowrap; float: right; /*position: absolute; margin:0; left:380px; top: 0px;*/ padding-right: 5%; clear: right; padding-bottom: 20px; } #nav-global li { display:block; float:left; list-style-type:none; margin:0; padding:0; } #nav-global a { display:block; float:left; /*font-family:"Trebuchet MS"; font-size: 110%; */ padding:42px 18px 7px 18px; background:#000000; color: #ccc; border: 0px; text-decoration: underline; } #nav-global a:hover { color:white; background: url(../img/main-nav-bg-on.png) bottom repeat-x; border: 0px; } ul#navlist { margin: 0; padding:0; padding-left: 5%; padding-top: 8px; color: #eee; line-height: 20px; } ul#navlist li { display: inline; } ul#navlist li a { /*font-family: Tahoma, sans-serif; font-size: 11px;font-weight: bold;*/ border: 1px solid #fff; /*padding: 0em 1em;*/ padding: 0 18px 0 18px; color: #000; margin-right: 9px; text-decoration: none; float: right; } ul#navlist li a#highlight , ul#navlist li a#highlight:hover { color: #555; padding-right: 33px; } ul#navlist li a:hover { color: #b11; } ul#navlist li.active a.active, ul#main-nav li.active a.active:hover { color: #b00; border: 1px solid #888; } /* Font Styles */ a, a:link, a:visited, a:active { color: #0040BB; text-decoration: none; border-bottom: 1px dotted #ccc; } a:hover{ color: #000; border-bottom: 1px dotted #000; } a.no-underline, a.no-underline:link, a.no-underline:visited, a.no-underline:active { border: 0px; } img.no-border{ border: 0px; } /* Paragraph Styles */ .last{ padding-bottom: 0px; margin-bottom: 0px; } .first{ margin-top: 0px; } blockquote { padding-left: 10px; padding-right: 10px; margin-left: 5px; margin-right: 0; border-left: #ddd; border-width: 0 0 0 1px; border-style: none none none solid; } p.first, form{ padding: 0px; margin: 0px; } .medium{ font-family: Verdana, Geneva, Arial, sans-serif; font-size: 11px; line-height: 19px; } .large{ font-size: 110%; } .small{ font-size: 90%; line-height: 150%; font-family: Verdana, sans-serif; color: #000; } p.indent{ padding-left: 15px; padding-bottom: 15px; } tt, code{ font-size: 130%; color: #800000; } pre{ /* border-top: 1px dotted #000; border-left: 1px dotted #000; border-right: 1px solid #999; border-bottom: 1px solid #999; background: #eee;*/ font-size: 120%; padding: 3px 5px 3px 10px; margin-right: 10px; } .go{ /*background: url(../img/go.png) no-repeat right bottom;*/ padding-right: 20px; } .help, a.help{ cursor: help; font-weight: normal; } div.feature-highlight{ width: 550px; background: #eee; margin-top: 0px; padding: 12px 15px 15px 15px; border-bottom: 1px solid #ccc; border-right: 1px solid #ddd; } /* Horizontal Rule */ div.hr { clear: both; line-height: 0px; font-size: 0px; margin: 0px; padding: 0px; /*height: 4px; url(../img/horizontal-rule.png) no-repeat;background: #000; margin-bottom: 20px; width: 770px;*/ } hr { height: 1em; visibility: hidden; margin: 0px; padding: 0px; } /* Form Styles */ .form-style input[type=submit]{ background: #87CD15; color: #fff; border-top: 1px solid #999; border-left: 1px solid #999; border-bottom: 1px solid #333; border-right: 1px solid #333; } .form-style input[type=text], textarea, input[type=file]{ font-family: Tahoma, sans-serif; font-size: 11px; color: #444; background: #EAFEC2; border: solid 1px #aaa; padding: 3px; } .form-style select{ font-family: Tahoma, sans-serif; font-size: 11px; color: #444; background: #EAFEC2; border: solid 1px #aaa; } /* Lists */ ul.large{ padding: 0 0 0 15px; margin: 0 0 15px 0px; } ul.large li a { font-weight: normal; } /* Header Styles */ h1.first{ margin-top: 0px; margin-bottom: 0px; border-bottom: 1px solid #666; background: #fFF; padding: 3px; } h1, h2, h3 { font-size: 170%; line-height: normal; font-weight: normal; font-family: Arial, sans-serif; color: #000000; text-decoration: none; /*margin: 0 0 12px 0; padding: 0;*/ text-align: left; } h2{ font-size: 140%; } h3 { font-size: 120%; } h4{ font-size: 100%; } h4.asterix{ /*background: url(../img/box-small.png) no-repeat left center;*/ padding: 0px 0px 0px 15px; margin: 0px; /*font-size: 110%; */ color: #000000; } .main-exception-bar { background: #f8f8f8; border-bottom: 1px solid #ccc; padding: 10px 0px; margin-bottom: 17px; } .main-exception { font-size: 200%; } span.main-exception { margin-left: 19px; margin-right: 10px; } code.main-exception { } /* Boxes */ #formats { margin: -17px 4px 4px 5px; font-size: 11px; color: #888; float: right; } #formats .title { color: #222; } #formats a { color: #22a; } #formats a:hover { border-bottom: 1px solid #33f; } #formats a.active { color: #0b0; border-bottom: none; } div.faq-box{ /*border-style: solid; border-color: #C6F27A; border-width: 1px;*/ /*background:url('../img/hatch-green.png');*/ padding: 10px; /*font-family: Verdana, Geneva, Arial, sans-serif; font-size: 11px; line-height: 17px;*/ } div.highlight-box{ border-style: solid; border-color: #cccccc; border-width: 1px; background:url('../img/hatch-yellow.png'); padding: 10px; color: #555; /*font-family: Verdana, Geneva, Arial, sans-serif; font-size: 11px; line-height: 17px;*/ } .box-top{ width: 518px; /*background: url(../img/box-top.png) no-repeat left top;*/ padding-top: 7px; margin-bottom: 15px; } .box-middle{ /*background: url(../img/box-middle.png) repeat-y left top;*/ } .box-bottom{ /*background: url(../img/box-bottom.png) no-repeat left bottom;*/ padding: 0 10px 11px 12px; } /* Utility Styles */ .content-padding{ padding: 0px 6.5% 40px 6.5%; } .sidebar-padding{ padding: 15px 15px 40px 25px; } .invisible{ visibility: hidden; font-size: 1px; padding: 0px; line-height: 0px; margin: 0px; } a.no-underline{ border: 0px; } img.no-border{ border: 0px; } br.clear{ clear: both; width: 100%; } /* Quotes */ .quote-top p{ padding: 0px; margin: 0px; } .quote-top{ font-family: tahoma; /*background: url(../img/quote-top.png) no-repeat left top;*/ padding-left: 25px; padding-top: 4px; } .quote-bottom{ /*background: url(../img/quote-bottom.png) no-repeat right bottom;*/ padding-right: 17px; padding-bottom: 7px; } .quote-author{ /*background: url(../img/quote-author.png) no-repeat left top;*/ padding-left: 20px; padding-bottom: 20px; } /* Footer Styles */ #footer{padding: 5px 5% 40px 5%;} #footer p{ color: #333; } #footer a{ font-weight: normal; } #footer a:visited{ color: #666; text-decoration: none; border-bottom: 1px dotted; } #footer a{ color: #888; font-weight: normal; } #footer a:hover{ color: #000; text-decoration: none; border-bottom: 1px dotted; } table { width: 100%; } tr.header { background-color: #006; color: #fff; } tr.even { background-color: #e8e8e8; } table.variables td { vertical-align: top; overflow: auto; } a.button { background-color: #ccc; border: 2px outset #aaa; color: #000; text-decoration: none; } a.button:hover { background-color: #ddd; } code.source { color: #006; } a.switch_source { color: #090; text-decoration: none; } a.show_locals { color: #090; text-decoration: none; } a.switch_source:hover { background-color: #ddd; } .source-highlight { background-color: #ff9; } .red { color:#FF0000; } .bold { font-weight: bold; } .hidden-data {display: none} #util-link a, #util-link a:link, #util-link a:visited, #util-link a:active { border-bottom: 2px outset #aaa } /* Mako Styles */ .stacktrace { margin:5px 5px 5px 5px; } .highlight { padding:0px 10px 0px 10px; background-color:#9F9FDF; } .nonhighlight { padding:0px; background-color:#DFDFDF; } .sample { padding:10px; margin:10px 10px 10px 10px; font-family:monospace; font-size: 110%; } .sampleline { padding:0px 10px 0px 10px; } .sourceline { margin:5px 5px 10px 5px; font-family:monospace; font-size: 110%;} WebError-0.10.3+dfsg/weberror/eval-media/minus.jpg0000664000000000000000000000054710770066101020435 0ustar rootrootÿØÿàJFIFÿÛC    $.' ",#(7),01444'9=82<.342ÿÛC  2!!22222222222222222222222222222222222222222222222222ÿÀ "ÿÄÿÄ$!4BTs’±ÿÄÿÄ!ÿÚ ?ÐZ”êTŒz9m¬ò’CÆéÔQ A7¿^ö‹ìg‹“Ü;îj—Î?äWÚQJ­M{Oh,ŸÿÙWebError-0.10.3+dfsg/weberror/eval-media/jquery.scrollTo-min.js0000664000000000000000000000327011013333004023020 0ustar rootroot/** * jQuery.ScrollTo - Easy element scrolling using jQuery. * Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses. * Date: 2/19/2008 * @author Ariel Flesler * @version 1.3.3 */ ;(function($){var o=$.scrollTo=function(a,b,c){o.window().scrollTo(a,b,c)};o.defaults={axis:'y',duration:1};o.window=function(){return $($.browser.safari?'body':'html')};$.fn.scrollTo=function(l,m,n){if(typeof m=='object'){n=m;m=0}n=$.extend({},o.defaults,n);m=m||n.speed||n.duration;n.queue=n.queue&&n.axis.length>1;if(n.queue)m/=2;n.offset=j(n.offset);n.over=j(n.over);return this.each(function(){var a=this,b=$(a),t=l,c,d={},w=b.is('html,body');switch(typeof t){case'number':case'string':if(/^([+-]=)?\d+(px)?$/.test(t)){t=j(t);break}t=$(t,this);case'object':if(t.is||t.style)c=(t=$(t)).offset()}$.each(n.axis.split(''),function(i,f){var P=f=='x'?'Left':'Top',p=P.toLowerCase(),k='scroll'+P,e=a[k],D=f=='x'?'Width':'Height';if(c){d[k]=c[p]+(w?0:e-b.offset()[p]);if(n.margin){d[k]-=parseInt(t.css('margin'+P))||0;d[k]-=parseInt(t.css('border'+P+'Width'))||0}d[k]+=n.offset[p]||0;if(n.over[p])d[k]+=t[D.toLowerCase()]()*n.over[p]}else d[k]=t[p];if(/^\d+$/.test(d[k]))d[k]=d[k]<=0?0:Math.min(d[k],h(D));if(!i&&n.queue){if(e!=d[k])g(n.onAfterFirst);delete d[k]}});g(n.onAfter);function g(a){b.animate(d,m,n.easing,a&&function(){a.call(this,l)})};function h(D){var b=w?$.browser.opera?document.body:document.documentElement:a;return b['scroll'+D]-b['client'+D]}})};function j(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);WebError-0.10.3+dfsg/weberror/eval-media/plus.jpg0000664000000000000000000000055110770066101020260 0ustar rootrootÿØÿàJFIFÿÛC    $.' ",#(7),01444'9=82<.342ÿÛC  2!!22222222222222222222222222222222222222222222222222ÿÀ "ÿÄÿÄ#"#4Ts’±ÿÄÿÄ!ÿÚ ?g®n½Ieº=%êiÈ‘>󧼎ìn.±¥ÜÄs±¥ÕU1Œ}\ÏpïºÅ7Ö?ä/°¢Zš2öžÐY?ÿÙWebError-0.10.3+dfsg/weberror/eval-media/jquery.scrollTo.js0000664000000000000000000001454711013333004022250 0ustar rootroot/** * jQuery.ScrollTo * Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses. * Date: 2/19/2008 * * @projectDescription Easy element scrolling using jQuery. * Tested with jQuery 1.2.1. On FF 2.0.0.11, IE 6, Opera 9.22 and Safari 3 beta. on Windows. * * @author Ariel Flesler * @version 1.3.3 * * @id jQuery.scrollTo * @id jQuery.fn.scrollTo * @param {String, Number, DOMElement, jQuery, Object} target Where to scroll the matched elements. * The different options for target are: * - A number position (will be applied to all axes). * - A string position ('44', '100px', '+=90', etc ) will be applied to all axes * - A jQuery/DOM element ( logically, child of the element to scroll ) * - A string selector, that will be relative to the element to scroll ( 'li:eq(2)', etc ) * - A hash { top:x, left:y }, x and y can be any kind of number/string like above. * @param {Number} duration The OVERALL length of the animation, this argument can be the settings object instead. * @param {Object} settings Hash of settings, optional. * @option {String} axis Which axis must be scrolled, use 'x', 'y', 'xy' or 'yx'. * @option {Number} duration The OVERALL length of the animation. * @option {String} easing The easing method for the animation. * @option {Boolean} margin If true, the margin of the target element will be deducted from the final position. * @option {Object, Number} offset Add/deduct from the end position. One number for both axes or { top:x, left:y }. * @option {Object, Number} over Add/deduct the height/width multiplied by 'over', can be { top:x, left:y } when using both axes. * @option {Boolean} queue If true, and both axis are given, the 2nd axis will only be animated after the first one ends. * @option {Function} onAfter Function to be called after the scrolling ends. * @option {Function} onAfterFirst If queuing is activated, this function will be called after the first scrolling ends. * @return {jQuery} Returns the same jQuery object, for chaining. * * @example $('div').scrollTo( 340 ); * * @example $('div').scrollTo( '+=340px', { axis:'y' } ); * * @example $('div').scrollTo( 'p.paragraph:eq(2)', 500, { easing:'swing', queue:true, axis:'xy' } ); * * @example var second_child = document.getElementById('container').firstChild.nextSibling; * $('#container').scrollTo( second_child, { duration:500, axis:'x', onAfter:function(){ * alert('scrolled!!'); * }}); * * @example $('div').scrollTo( { top: 300, left:'+=200' }, { offset:-20 } ); * * Notes: * - jQuery.scrollTo will make the whole window scroll, it accepts the same arguments as jQuery.fn.scrollTo. * - If you are interested in animated anchor navigation, check http://jquery.com/plugins/project/LocalScroll. * - The options margin, offset and over are ignored, if the target is not a jQuery object or a DOM element. * - The option 'queue' won't be taken into account, if only 1 axis is given. */ ;(function( $ ){ var $scrollTo = $.scrollTo = function( target, duration, settings ){ $scrollTo.window().scrollTo( target, duration, settings ); }; $scrollTo.defaults = { axis:'y', duration:1 }; //returns the element that needs to be animated to scroll the window $scrollTo.window = function(){ return $( $.browser.safari ? 'body' : 'html' ); }; $.fn.scrollTo = function( target, duration, settings ){ if( typeof duration == 'object' ){ settings = duration; duration = 0; } settings = $.extend( {}, $scrollTo.defaults, settings ); duration = duration || settings.speed || settings.duration;//speed is still recognized for backwards compatibility settings.queue = settings.queue && settings.axis.length > 1;//make sure the settings are given right if( settings.queue ) duration /= 2;//let's keep the overall speed, the same. settings.offset = both( settings.offset ); settings.over = both( settings.over ); return this.each(function(){ var elem = this, $elem = $(elem), t = target, toff, attr = {}, win = $elem.is('html,body'); switch( typeof t ){ case 'number'://will pass the regex case 'string': if( /^([+-]=)?\d+(px)?$/.test(t) ){ t = both( t ); break;//we are done } t = $(t,this);// relative selector, no break! case 'object': if( t.is || t.style )//DOM/jQuery toff = (t = $(t)).offset();//get the real position of the target } $.each( settings.axis.split(''), function( i, axis ){ var Pos = axis == 'x' ? 'Left' : 'Top', pos = Pos.toLowerCase(), key = 'scroll' + Pos, act = elem[key], Dim = axis == 'x' ? 'Width' : 'Height', dim = Dim.toLowerCase(); if( toff ){//jQuery/DOM attr[key] = toff[pos] + ( win ? 0 : act - $elem.offset()[pos] ); if( settings.margin ){//if it's a dom element, reduce the margin attr[key] -= parseInt(t.css('margin'+Pos)) || 0; attr[key] -= parseInt(t.css('border'+Pos+'Width')) || 0; } attr[key] += settings.offset[pos] || 0;//add/deduct the offset if( settings.over[pos] )//scroll to a fraction of its width/height attr[key] += t[dim]() * settings.over[pos]; }else attr[key] = t[pos];//remove the unnecesary 'px' if( /^\d+$/.test(attr[key]) )//number or 'number' attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max(Dim) );//check the limits if( !i && settings.queue ){//queueing each axis is required if( act != attr[key] )//don't waste time animating, if there's no need. animate( settings.onAfterFirst );//intermediate animation delete attr[key];//don't animate this axis again in the next iteration. } }); animate( settings.onAfter ); function animate( callback ){ $elem.animate( attr, duration, settings.easing, callback && function(){ callback.call(this, target); }); }; function max( Dim ){ var el = win ? $.browser.opera ? document.body : document.documentElement : elem; return el['scroll'+Dim] - el['client'+Dim]; }; }); }; function both( val ){ return typeof val == 'object' ? val : { top:val, left:val }; }; })( jQuery );WebError-0.10.3+dfsg/weberror/eval-media/debug.js0000664000000000000000000002521011126232531020214 0ustar rootrootfunction showFrame(anchor) { var tbid = anchor.getAttribute('tbid'); var expanded = anchor.expanded; if (expanded) { hideElement(anchor.expandedElement); anchor.expanded = false; _swapImage(anchor); return false; } anchor.expanded = true; if (anchor.expandedElement) { showElement(anchor.expandedElement); _swapImage(anchor); $('#debug_input_'+tbid).get(0).focus(); return false; } var url = debug_base + '/show_frame?tbid=' + tbid + '&debugcount=' + debug_count; callbackXHR(url, null, function (data) { var el = createElement('div'); anchor.parentNode.insertBefore(el, anchor.nextSibling); el.innerHTML = data.responseText; anchor.expandedElement = el; _swapImage(anchor); $('#debug_input_'+tbid).focus().keydown(upArrow); }); return false; } function _swapImage(anchor) { var el = anchor.getElementsByTagName('IMG')[0]; if (anchor.expanded) { var img = 'minus.jpg'; } else { var img = 'plus.jpg'; } el.src = debug_base + '/media/' + img; } function showSource(anchor) { var location = anchor.getAttribute('location'); showSourceCode(location); return false; } function showSourceCode(location) { var url = debug_base + '/source_code?location=' + encodeURIComponent(location); var source = document.getElementById('source_data'); source.innerHTML = 'Loading...'; switch_display('source_data'); callbackXHR(url, null, function (req) { source.innerHTML = req.responseText; if (location.indexOf(':') > 0) { var lineno = location.substring(location.indexOf(':')+1); lineno = parseInt(lineno) - 10; if (lineno > 1) { document.location.hash = '#code-'+(lineno-10); } } }); } function submitInput(button, tbid) { var input = $('#' + button.getAttribute('input-from')).get(0); var output = $('#' + button.getAttribute('output-to')).get(0); var url = debug_base + '/exec_input'; var history = input.form.history; input.historyPosition = 0; if (! history) { history = input.form.history = []; } history.push(input.value); var vars = { tbid: tbid, debugcount: debug_count, input: input.value }; showElement(output); callbackXHR(url, vars, function (data) { var result = data.responseText; output.innerHTML += result; input.value = ''; input.focus(); }); return false; } function showError(msg) { var el = $('#error-container').get(0); if (el.innerHTML) { el.innerHTML += '
\n' + msg; } else { el.innerHTML = msg; } showElement($('#error-area').get(0)); } function clearError() { var el = $('#error-container').get(0); el.innerHTML = ''; $('#error-area').hide(); } function upArrow(event) { var key = event.charCode ? event.charCode : event.keyCode; if (key != 38 && key != 40 && key != 63232 && key != 63233) { // not an up- or down-arrow return true; } var dir = ((key == 38) || (key == 63232)) ? 1 : -1; var history = this.form.history; if (! history) { history = this.form.history = []; } var pos = this.historyPosition || 0; if (! pos && dir == -1) { return true; } if (! pos && this.value) { history.push(this.value); pos = 1; } pos += dir; if (history.length-pos < 0) { pos = 1; } if (history.length-pos > history.length-1) { this.value = ''; return true; } this.historyPosition = pos; var line = history[history.length-pos]; if (! line) { return true; } this.value = line; } function expandInput(button) { var input = button.form.elements.input; stdops = { name: 'input', style: 'width: 100%', autocomplete: 'off' }; if (input.tagName == 'INPUT') { var newEl = createElement('textarea', stdops); var text = 'Contract'; } else { stdops['type'] = 'text'; var newEl = createElement('input', stdops); $(newEl).keydown(upArrow); var text = 'Expand'; } newEl.value = input.value; newEl.id = input.id; swapDOM(input, newEl); newEl.focus(); button.value = text; return false; } function expandLong(anchor) { var span = anchor; while (span) { if (span.style && span.style.display == 'none') { break; } span = span.nextSibling; } if (! span) { return false; } showElement(span); hideElement(anchor); return false; } function showElement(el) { el.style.display = ''; } function hideElement(el) { el.style.display = 'none'; } function createElement(tag, attrs /*, sub-elements...*/) { var el = document.createElement(tag); if (attrs) { for (var i in attrs) { el.setAttribute(i, attrs[i]); } } for (var i=2; i' + name + '
'); } function switch_source(el, hide_type) { while (el) { if (el.getAttribute && el.getAttribute('source-type') == hide_type) { break; } el = el.parentNode; } if (! el) { return false; } el.style.display = 'none'; console.log('found current el', el); if (hide_type == 'long') { while (el) { if (el.getAttribute && el.getAttribute('source-type') == 'short') { break; } el = el.nextSibling; } console.log('found short el', el); } else { while (el) { if (el.getAttribute && el.getAttribute('source-type') == 'long') { break; } el = el.previousSibling; } console.log('found long el', el); } if (el) { el.style.display = ''; } return false; } $(document).ready(function() { var hide_all = function() { $('#short_text_version, #long_text_version, #short_traceback, #full_traceback, #short_xml_version, #long_xml_version, div.feature-highlight').hide(); $('#view_long_text, #view_short_text, #view_long_html, #view_short_html, #view_short_xml, #view_long_xml').removeClass('active'); }; if ($('#long_text_version').length == 0) { $('#view_long_text').hide(); } if ($('#full_traceback').length == 0) { $('#view_long_html').hide(); } $('#view_short_text').click(function() { hide_all(); $('#short_text_version').show(); $(this).addClass('active'); return false; }); $('#view_long_text').click(function() { hide_all(); $('#long_text_version').show(); $(this).addClass('active'); return false; }); $('#view_short_html').click(function() { hide_all(); $('#short_traceback, div.feature-highlight').show(); $(this).addClass('active'); return false; }); $('#view_long_html').click(function () { hide_all(); $('#full_traceback, div.feature-highlight').show(); $(this).addClass('active'); return false; }); $('#view_short_xml').click(function () { hide_all(); $('#short_xml_version').show(); $(this).addClass('active'); return false; }); $('#view_long_xml').click(function () { hide_all(); $('#long_xml_version').show(); $(this).addClass('active'); return false; }); }); /* Fix case when Firebug isn't present: */ if (typeof console == 'undefined') { var console = {log: function (msg) {}}; } WebError-0.10.3+dfsg/weberror/eval_template.html0000664000000000000000000001140511126232531020275 0ustar rootroot Server Error {{head_html|html}}

There is no source code to display. Click a 'view' link in the Traceback tab to load source code.
{{for extra_data_item in extra_data:}}

Extra Data

{{extra_data_item|html}} {{endfor}}
{{template_data|html}}

WebError Traceback:

{{exc_name}}: {{formatted_exc_value|html}}
View as:   Interactive (full)  |  Text (full)  |  XML (full)
{{traceback_body|html}}
Extra Features
>>Display the lines of code near each part of the traceback
Show a debug prompt to allow you to directly debug the code at the traceback
{{repost_button|html}}


WebError-0.10.3+dfsg/weberror/formatter.py0000664000000000000000000006515111335430006017150 0ustar rootroot# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org) # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php """ Formatters for the exception data that comes from ExceptionCollector. """ # @@: TODO: # Use this: http://www.zope.org/Members/tino/VisualTraceback/VisualTracebackNews import cgi import re import sys from weberror.util import escaping from xml.dom.minidom import getDOMImplementation from pygments import highlight as pygments_highlight from pygments.lexers import ClassNotFound, PythonLexer, TextLexer, \ get_lexer_for_filename from pygments.formatters import HtmlFormatter try: import pkg_resources except ImportError: pkg_resources = None def html_quote(s): return cgi.escape(str(s), True) pygments_css = HtmlFormatter().get_style_defs('.highlight') def highlight(filename, code, linenos=False, lineanchors=None, cssclass='highlight'): if lineanchors is None and linenos: lineanchors = 'code' lexer = None if filename: if filename.endswith('.py'): # XXX: Pygments gives back NumPyLexer for some reason, which # we don't need lexer = PythonLexer() else: try: lexer = get_lexer_for_filename(filename) except ClassNotFound: pass if not lexer: lexer = TextLexer() formatter = HtmlFormatter(linenos=linenos, lineanchors=lineanchors, cssclass=cssclass) return pygments_highlight(code, lexer, formatter) class AbstractFormatter(object): general_data_order = ['object', 'source_url'] def __init__(self, show_hidden_frames=False, include_reusable=True, show_extra_data=True, trim_source_paths=(), **kwargs): self.show_hidden_frames = show_hidden_frames self.trim_source_paths = trim_source_paths self.include_reusable = include_reusable self.show_extra_data = show_extra_data self.extra_kwargs = kwargs def format_collected_data(self, exc_data): general_data = {} if self.show_extra_data: for name, value_list in exc_data.extra_data.items(): if isinstance(name, tuple): importance, title = name else: importance, title = 'normal', name for value in value_list: general_data[(importance, name)] = self.format_extra_data( importance, title, value) lines = [] frames = self.filter_frames(exc_data.frames) for frame in frames: self.frame = frame res = self.format_frame_start(frame) if res: lines.append(res) sup = frame.supplement if sup: if sup.object: general_data[('important', 'object')] = self.format_sup_object( sup.object) if sup.source_url: general_data[('important', 'source_url')] = self.format_sup_url( sup.source_url) if sup.line: lines.append(self.format_sup_line_pos(sup.line, sup.column)) if sup.expression: lines.append(self.format_sup_expression(sup.expression)) if sup.warnings: for warning in sup.warnings: lines.append(self.format_sup_warning(warning)) if sup.info: lines.extend(self.format_sup_info(sup.info)) if frame.supplement_exception: lines.append('Exception in supplement:') lines.append(self.quote_long(frame.supplement_exception)) if frame.traceback_info: lines.append(self.format_traceback_info(frame.traceback_info)) filename = frame.filename if filename and self.trim_source_paths: for path, repl in self.trim_source_paths: if filename.startswith(path): filename = repl + filename[len(path):] break lines.append(self.format_source_line(filename or '?', frame)) source = frame.get_source_line() long_source = frame.get_source_line(2) if source: lines.append(self.format_long_source(filename, source, long_source)) res = self.format_frame_end(frame) if res: lines.append(res) etype = exc_data.exception_type if not isinstance(etype, basestring): etype = etype.__name__ exc_info = self.format_exception_info( etype, exc_data.exception_value) data_by_importance = {'important': [], 'normal': [], 'supplemental': [], 'extra': []} for (importance, name), value in general_data.items(): data_by_importance[importance].append( (name, value)) for value in data_by_importance.values(): value.sort() return self.format_combine(data_by_importance, lines, exc_info) def filter_frames(self, frames): """ Removes any frames that should be hidden, according to the values of traceback_hide, self.show_hidden_frames, and the hidden status of the final frame. """ if self.show_hidden_frames: return frames new_frames = [] hidden = False for frame in frames: hide = frame.traceback_hide # @@: It would be nice to signal a warning if an unknown # hide string was used, but I'm not sure where to put # that warning. if hide == 'before': new_frames = [] hidden = False elif hide == 'before_and_this': new_frames = [] hidden = False continue elif hide == 'reset': hidden = False elif hide == 'reset_and_this': hidden = False continue elif hide == 'after': hidden = True elif hide == 'after_and_this': hidden = True continue elif hide: continue elif hidden: continue new_frames.append(frame) if frames[-1] not in new_frames: # We must include the last frame; that we don't indicates # that the error happened where something was "hidden", # so we just have to show everything return frames return new_frames def format_frame_start(self, frame): """ Called before each frame starts; may return None to output no text. """ return None def format_frame_end(self, frame): """ Called after each frame ends; may return None to output no text. """ return None def pretty_string_repr(self, s): """ Formats the string as a triple-quoted string when it contains newlines. """ if '\n' in s: s = repr(s) s = s[0]*3 + s[1:-1] + s[-1]*3 s = s.replace('\\n', '\n') return s else: return repr(s) def long_item_list(self, lst): """ Returns true if the list contains items that are long, and should be more nicely formatted. """ how_many = 0 for item in lst: if len(repr(item)) > 40: how_many += 1 if how_many >= 3: return True return False class TextFormatter(AbstractFormatter): def quote(self, s): if isinstance(s, str) and hasattr(self, 'frame'): s = s.decode(self.frame.source_encoding, 'replace') return s.encode('latin1', 'htmlentityreplace') def quote_long(self, s): return self.quote(s) def emphasize(self, s): return s def format_sup_object(self, obj): return 'In object: %s' % self.emphasize(self.quote(repr(obj))) def format_sup_url(self, url): return 'URL: %s' % self.quote(url) def format_sup_line_pos(self, line, column): if column: return self.emphasize('Line %i, Column %i' % (line, column)) else: return self.emphasize('Line %i' % line) def format_sup_expression(self, expr): return self.emphasize('In expression: %s' % self.quote(expr)) def format_sup_warning(self, warning): return 'Warning: %s' % self.quote(warning) def format_sup_info(self, info): return [self.quote_long(info)] def format_source_line(self, filename, frame): return 'File %r, line %s in %s' % ( filename, frame.lineno or '?', frame.name or '?') def format_long_source(self, filename, source, long_source): return self.format_source(filename, source) def format_source(self, filename, source_line): return ' ' + self.quote(source_line.strip()) def format_exception_info(self, etype, evalue): return self.emphasize( '%s: %s' % (self.quote(etype), self.quote(evalue))) def format_traceback_info(self, info): return info def format_combine(self, data_by_importance, lines, exc_info): lines[:0] = [value for n, value in data_by_importance['important']] lines.append(exc_info) for name in 'normal', 'supplemental', 'extra': lines.extend([value for n, value in data_by_importance[name]]) return self.format_combine_lines(lines), '' def format_combine_lines(self, lines): return '\n'.join([convert_to_str(line) for line in lines]) def format_extra_data(self, importance, title, value): if isinstance(value, str): s = self.pretty_string_repr(value) if '\n' in s: return '%s:\n%s' % (title, s) else: return '%s: %s' % (title, s) elif isinstance(value, dict): lines = ['\n', title, '-'*len(title)] items = value.items() items.sort() for n, v in items: try: v = repr(v) except Exception, e: v = 'Cannot display: %s' % e v = truncate(v) lines.append(' %s: %s' % (n, v)) return '\n'.join(lines) elif (isinstance(value, (list, tuple)) and self.long_item_list(value)): parts = [truncate(repr(v)) for v in value] return '%s: [\n %s]' % ( title, ',\n '.join(parts)) else: return '%s: %s' % (title, truncate(repr(value))) class HTMLFormatter(TextFormatter): def quote(self, s): if isinstance(s, str) and hasattr(self, 'frame'): s = s.decode(self.frame.source_encoding, 'replace') s = s.encode('latin1', 'htmlentityreplace') return html_quote(s) def quote_long(self, s): return '
%s
' % self.quote(s) def emphasize(self, s): return '%s' % s def format_sup_url(self, url): return 'URL: %s' % (url, url) def format_combine_lines(self, lines): ## FIXME: this is horrible: new_lines = [] for line in lines: if not line.startswith(''): line += '
' new_lines.append(convert_to_str(line)) return '\n'.join(new_lines) def format_source_line(self, filename, frame): self.frame = frame name = self.quote(frame.name or '?') return 'Module %s:%s in %s' % ( filename, frame.modname or '?', frame.lineno or '?', name) def format_long_source(self, filename, source, long_source): q_long_source = str2html(long_source, False, 4, True, getattr(self, 'frame', None), filename=filename) q_source = str2html(source, True, 0, False, getattr(self, 'frame', None), filename=filename) return ('' '' % (q_long_source, q_source)) def format_source(self, filename, source_line): return '  %s' % self.quote(source_line.strip()) def format_traceback_info(self, info): return '
%s
' % self.quote(info) def format_frame_start(self, frame): ## FIXME: make it zebra? return '
' def format_frame_end(self, frame): return '
' def format_extra_data(self, importance, title, value): if isinstance(value, str): s = self.pretty_string_repr(value) if '\n' in s: return '%s:
%s
' % (title, self.quote(s)) else: return '%s: %s' % (title, self.quote(s)) elif isinstance(value, dict): return self.zebra_table(title, value) elif (isinstance(value, (list, tuple)) and self.long_item_list(value)): return '%s: [
\n    %s]
' % ( title, ',
    '.join(map(self.quote, map(repr, value)))) else: return '%s: %s' % (title, self.quote(repr(value))) def format_combine(self, data_by_importance, lines, exc_info): lines[:0] = [value for n, value in data_by_importance['important']] lines.append(exc_info) for name in 'normal', 'supplemental': lines.extend([value for n, value in data_by_importance[name]]) extra_data = [] if data_by_importance['extra']: extra_data.extend([value for n, value in data_by_importance['extra']]) text = self.format_combine_lines(lines) ## FIXME: something about this is wrong: if self.include_reusable: return text, extra_data else: # Usually because another error is already on this page, # and so the js & CSS are unneeded return text, extra_data def zebra_table(self, title, rows, table_class="variables"): if isinstance(rows, dict): rows = rows.items() rows.sort() table = ['' % table_class, '' % self.quote(title)] odd = False for name, value in rows: try: value = repr(value) except Exception, e: value = 'Cannot print: %s' % e odd = not odd table.append( '' % (odd and 'odd' or 'even', self.quote(name))) table.append( '' % make_wrappable(self.quote(truncate(value)))) table.append('
%s
%s%s
') return '\n'.join(table) def get_dependencies(circ_check, lib, working_set): libs = {} for proj in working_set.by_key[lib].requires(): if proj.key in circ_check: continue circ_check[proj.key] = True libs[proj.key] = working_set.by_key[proj.key].version libs.update(get_dependencies(circ_check, proj.key, working_set)) return libs def get_libraries(libs=None): """Return a dict of the desired libraries and their version if active in the environment""" if pkg_resources and libs: libraries = {} working_set = pkg_resources.working_set for lib in libs: # Put libs we've either check dependencies on, or are in progress # of checking here, to avoid circular references going forever circ_check = {} if lib in working_set.by_key: if lib in circ_check: continue circ_check[lib] = True libraries[lib] = working_set.by_key[lib].version libraries.update( get_dependencies(circ_check, lib, working_set)) return libraries else: return {} def create_text_node(doc, elem, text): if not isinstance(text, basestring): try: text = escaping.removeIllegalChars(repr(text)) except: text = 'UNABLE TO GET TEXT REPRESENTATION' new_elem = doc.createElement(elem) new_elem.appendChild(doc.createTextNode(text)) return new_elem class XMLFormatter(AbstractFormatter): def format_collected_data(self, exc_data): impl = getDOMImplementation() newdoc = impl.createDocument(None, "traceback", None) top_element = newdoc.documentElement sysinfo = newdoc.createElement('sysinfo') language = create_text_node(newdoc, 'language', 'Python') language.attributes['version'] = sys.version.split(' ')[0] language.attributes['full_version'] = sys.version language.attributes['platform'] = sys.platform sysinfo.appendChild(language) # Pull out pkg_resource libraries for set libraries libs = get_libraries(self.extra_kwargs.get('libraries')) if libs: libraries = newdoc.createElement('libraries') for k, v in libs.iteritems(): lib = newdoc.createElement('library') lib.attributes['version'] = v lib.attributes['name'] = k libraries.appendChild(lib) sysinfo.appendChild(libraries) top_element.appendChild(sysinfo) frames = self.filter_frames(exc_data.frames) stack = newdoc.createElement('stack') top_element.appendChild(stack) for frame in frames: xml_frame = newdoc.createElement('frame') stack.appendChild(xml_frame) filename = frame.filename if filename and self.trim_source_paths: for path, repl in self.trim_source_paths: if filename.startswith(path): filename = repl + filename[len(path):] break self.format_source_line(filename or '?', frame, newdoc, xml_frame) source = frame.get_source_line() long_source = frame.get_source_line(2) if source: self.format_long_source(filename, source.decode(frame.source_encoding, 'replace'), long_source.decode(frame.source_encoding, 'replace'), newdoc, xml_frame) # @@@ TODO: Put in a way to optionally toggle including variables # variables = newdoc.createElement('variables') # xml_frame.appendChild(variables) # for name, value in frame.locals.iteritems(): # if isinstance(value, unicode): # value = value.encode('ascii', 'xmlcharrefreplace') # variable = newdoc.createElement('variable') # variable.appendChild(create_text_node(newdoc, 'name', name)) # variable.appendChild(create_text_node(newdoc, 'value', value)) # variables.appendChild(variable) etype = exc_data.exception_type if not isinstance(etype, basestring): etype = etype.__name__ top_element.appendChild(self.format_exception_info( etype, exc_data.exception_value, newdoc, frame)) return newdoc.toxml(), '' def format_source_line(self, filename, frame, newdoc, xml_frame): name = frame.name or '?' xml_frame.appendChild(create_text_node(newdoc, 'module', frame.modname or '?')) xml_frame.appendChild(create_text_node(newdoc, 'filename', filename)) xml_frame.appendChild(create_text_node(newdoc, 'line', str(frame.lineno) or '?')) xml_frame.appendChild(create_text_node(newdoc, 'function', name)) def format_long_source(self, filename, source, long_source, newdoc, xml_frame): source = source.encode('ascii', 'xmlcharrefreplace') long_source = long_source.encode('ascii', 'xmlcharrefreplace') xml_frame.appendChild(create_text_node(newdoc, 'operation', source.strip())) xml_frame.appendChild(create_text_node(newdoc, 'operation_context', long_source)) def format_exception_info(self, etype, evalue, newdoc, frame): exception = newdoc.createElement('exception') evalue = evalue.decode( frame.source_encoding, 'replace').encode('ascii', 'xmlcharrefreplace') exception.appendChild(create_text_node(newdoc, 'type', etype)) exception.appendChild(create_text_node(newdoc, 'value', evalue)) return exception def format_html(exc_data, include_hidden_frames=False, **ops): if not include_hidden_frames: return HTMLFormatter(**ops).format_collected_data(exc_data) short_er = None if not include_hidden_frames: short_er, head_html = format_html(exc_data, show_hidden_frames=False, **ops) ops['include_reusable'] = False ops['show_extra_data'] = False long_er, head_html = format_html(exc_data, show_hidden_frames=True, **ops) if not include_hidden_frames and short_er == long_er: # Suppress the short error if it is identical to the long one short_er = None text_er, head_text = format_text(exc_data, show_hidden_frames=True, **ops) xml_er, head_xml = format_xml(exc_data, show_hidden_frames=True, **ops) if short_er: short_er = '
%s
\n' % short_er return """ %s %s
%s
""" % ('\n'.join(head_html), short_er or '', long_er, cgi.escape(text_er), cgi.escape(xml_er)) def format_text(exc_data, **ops): return TextFormatter(**ops).format_collected_data(exc_data) def format_xml(exc_data, **ops): return XMLFormatter(**ops).format_collected_data(exc_data) whitespace_re = re.compile(r' +') pre_re = re.compile(r'') error_re = re.compile(r'

ERROR: .*?

') def str2html(src, strip=False, indent_subsequent=0, highlight_inner=False, frame=None, filename=None): """ Convert a string to HTML. Try to be really safe about it, returning a quoted version of the string if nothing else works. """ try: return _str2html(src, strip=strip, indent_subsequent=indent_subsequent, highlight_inner=highlight_inner, frame=frame, filename=filename) except: if isinstance(src, str) and frame: src = src.decode(frame.source_encoding, 'replace') src = src.encode('latin1', 'htmlentityreplace') return src return html_quote(src) def _str2html(src, strip=False, indent_subsequent=0, highlight_inner=False, frame=None, filename=None): if strip: src = src.strip() orig_src = src try: src = highlight(filename, src) src = error_re.sub('', src) src = pre_re.sub('', src) src = re.sub(r'^[\n\r]{0,1}', '', src) src = re.sub(r'[\n\r]{0,1}$', '', src) # This gets rid of the
that Pygments adds: if src.strip().startswith('
') and \ src.strip().endswith('
'): src = src.strip()[len('
'):-len('
')] if isinstance(src, str) and frame: src = src.decode(frame.source_encoding, 'replace') src = src.encode('latin1', 'htmlentityreplace') except: if isinstance(src, str) and frame: src = src.decode(frame.source_encoding, 'replace') src = src.encode('latin1', 'htmlentityreplace') else: src = html_quote(orig_src) lines = src.splitlines() if len(lines) == 1: return lines[0] # XXX: Lame variable width font, I think, requires +3 padding indent_subsequent += 3 indent = ' '*indent_subsequent for i in range(1, len(lines)): lines[i] = indent+lines[i] if highlight_inner and i == len(lines)/2: lines[i] = '%s' % lines[i] src = '
\n'.join(lines) src = whitespace_re.sub( lambda m: ' '*(len(m.group(0))-1) + ' ', src) return src def truncate(string, limit=1000): """ Truncate the string to the limit number of characters """ if len(string) > limit: return string[:limit-20]+'...'+string[-17:] else: return string def make_wrappable(html, wrap_limit=60, split_on=';?&@!$#-/\\"\''): # Currently using , maybe should use ​ # http://www.cs.tut.fi/~jkorpela/html/nobr.html if len(html) <= wrap_limit: return html words = html.split() new_words = [] for word in words: wrapped_word = '' while len(word) > wrap_limit: for char in split_on: if char in word: first, rest = word.split(char, 1) wrapped_word += first+char+'' word = rest break else: for i in range(0, len(word), wrap_limit): wrapped_word += word[i:i+wrap_limit]+'' word = '' wrapped_word += word new_words.append(wrapped_word) return ' '.join(new_words) def make_pre_wrappable(html, wrap_limit=60, split_on=';?&@!$#-/\\"\''): """ Like ``make_wrappable()`` but intended for text that will go in a ``
`` block, so wrap on a line-by-line basis.
    """
    lines = html.splitlines()
    new_lines = []
    for line in lines:
        if len(line) > wrap_limit:
            for char in split_on:
                if char in line:
                    parts = line.split(char)
                    line = ''.join(parts)
                    break
        new_lines.append(line)
    return '\n'.join(lines)

def convert_to_str(s):
    if isinstance(s, unicode):
        return s.encode('utf8')
    return s
WebError-0.10.3+dfsg/weberror/evalexception.py0000664000000000000000000007261311164461161020022 0ustar  rootroot"""Exception-catching middleware that allows interactive debugging.

This middleware catches all unexpected exceptions.  A normal
traceback, like produced by
``weberror.exceptions.errormiddleware.ErrorMiddleware`` is given, plus
controls to see local variables and evaluate expressions in a local
context.

This can only be used in single-process environments, because
subsequent requests must go back to the same process that the
exception originally occurred in.  Threaded or non-concurrent
environments both work.

This shouldn't be used in production in any way.  That would just be
silly.

If calling from an XMLHttpRequest call, if the GET variable ``_`` is
given then it will make the response more compact (and less
Javascripty), since if you use innerHTML it'll kill your browser.  You
can look for the header X-Debug-URL in your 500 responses if you want
to see the full debuggable traceback.  Also, this URL is printed to
``wsgi.errors``, so you can open it up in another browser window.

"""
import httplib
import sys
import os
import cgi
import traceback
from cStringIO import StringIO
import pprint
import itertools
import time
import re
import types
import urllib

from pkg_resources import resource_filename

from paste import fileapp
from paste import registry
from paste import request
from paste import urlparser
from paste.util import import_string

import evalcontext
from weberror import errormiddleware, formatter, collector
from weberror.util import escaping
from tempita import HTMLTemplate
from webob import Request, Response
from webob import exc

limit = 200

def html_quote(v):
    """
    Escape HTML characters, plus translate None to ''
    """
    if v is None:
        return ''
    return cgi.escape(str(v), 1)

def preserve_whitespace(v, quote=True):
    """
    Quote a value for HTML, preserving whitespace (translating
    newlines to ``
`` and multiple spaces to use `` ``). If ``quote`` is true, then the value will be HTML quoted first. """ if quote: v = html_quote(v) v = v.replace('\n', '
\n') v = re.sub(r'()( +)', _repl_nbsp, v) v = re.sub(r'(\n)( +)', _repl_nbsp, v) v = re.sub(r'^()( +)', _repl_nbsp, v) return '%s' % v def _repl_nbsp(match): if len(match.group(2)) == 1: return ' ' return match.group(1) + ' ' * (len(match.group(2))-1) + ' ' def simplecatcher(application): """ A simple middleware that catches errors and turns them into simple tracebacks. """ def simplecatcher_app(environ, start_response): try: return application(environ, start_response) except: out = StringIO() traceback.print_exc(file=out) start_response('500 Server Error', [('content-type', 'text/html')], sys.exc_info()) res = out.getvalue() return ['

Error

%s
' % html_quote(res)] return simplecatcher_app def wsgiapp(): """ Turns a function or method into a WSGI application. """ def decorator(func): def wsgiapp_wrapper(*args): # we get 3 args when this is a method, two when it is # a function :( if len(args) == 3: environ = args[1] start_response = args[2] args = [args[0]] else: environ, start_response = args args = [] def application(environ, start_response): form = request.parse_formvars(environ, include_get_vars=True) status = '200 OK' form['environ'] = environ try: res = func(*args, **form.mixed()) except ValueError, ve: status = '500 Server Error' res = 'There was an error: %s' % \ html_quote(ve) start_response(status, [('content-type', 'text/html')]) return [res] app = simplecatcher(application) return app(environ, start_response) wsgiapp_wrapper.exposed = True return wsgiapp_wrapper return decorator def get_debug_info(func): """ A decorator (meant to be used under ``wsgiapp()``) that resolves the ``debugcount`` variable to a ``DebugInfo`` object (or gives an error if it can't be found). """ def debug_info_replacement(self, req): if 'debugcount' not in req.params: return exc.HTTPBadRequest( "You must provide a debugcount parameter") debugcount = req.params['debugcount'] try: debugcount = int(debugcount) except ValueError, e: return exc.HTTPBadRequest( "Invalid value for debugcount (%r): %s" % (debugcount, e)) if debugcount not in self.debug_infos: return exc.HTTPServerError( "Debug %s not found (maybe it has expired, or the server was restarted)" % debugcount) req.debug_info = self.debug_infos[debugcount] return func(self, req) debug_info_replacement.exposed = True return debug_info_replacement debug_counter = itertools.count(int(time.time())) def get_debug_count(req): """ Return the unique debug count for the current request """ if hasattr(req, 'environ'): environ = req.environ else: environ = req # XXX: Legacy support for Paste restorer if 'paste.evalexception.debug_count' in environ: return environ['paste.evalexception.debug_count'] elif 'weberror.evalexception.debug_count' in environ: return environ['weberror.evalexception.debug_count'] else: next = debug_counter.next() environ['weberror.evalexception.debug_count'] = next environ['paste.evalexception.debug_count'] = next return next class InvalidTemplate(Exception): pass class EvalException(object): """Handles capturing an exception and turning it into an interactive exception explorer""" def __init__(self, application, global_conf=None, error_template_filename=None, xmlhttp_key=None, media_paths=None, templating_formatters=None, head_html='', footer_html='', reporters=None, libraries=None, **params): self.libraries = libraries or [] self.application = application self.debug_infos = {} self.templating_formatters = templating_formatters or [] self.head_html = HTMLTemplate(head_html) self.footer_html = HTMLTemplate(footer_html) if error_template_filename is None: error_template_filename = resource_filename( "weberror", "eval_template.html" ) if xmlhttp_key is None: if global_conf is None: xmlhttp_key = '_' else: xmlhttp_key = global_conf.get('xmlhttp_key', '_') self.xmlhttp_key = xmlhttp_key self.media_paths = media_paths or {} self.error_template = HTMLTemplate.from_filename(error_template_filename) if reporters is None: reporters = [] self.reporters = reporters def __call__(self, environ, start_response): ## FIXME: print better error message (maybe fall back on ## normal middleware, plus an error message) assert not environ['wsgi.multiprocess'], ( "The EvalException middleware is not usable in a " "multi-process environment") # XXX: Legacy support for Paste restorer environ['weberror.evalexception'] = environ['paste.evalexception'] = \ self req = Request(environ) if req.path_info_peek() == '_debug': return self.debug(req)(environ, start_response) else: return self.respond(environ, start_response) def debug(self, req): assert req.path_info_pop() == '_debug' next_part = req.path_info_pop() method = getattr(self, next_part, None) if method is None: return exc.HTTPNotFound('Nothing could be found to match %r' % next_part) if not getattr(method, 'exposed', False): return exc.HTTPForbidden('Access to %r is forbidden' % next_part) return method(req) def relay(self, req): """Relay a request to a remote machine for JS proxying""" host = req.GET['host'] conn = httplib.HTTPConnection(host) headers = req.headers # Re-assemble the query string query_str = {} for param, val in req.GET.iteritems(): if param in ['host', 'path']: continue query_str[param] = val query_str = urllib.urlencode(query_str) # Transport a GET or a POST if req.method == 'GET': conn.request("GET", '%s?%s' % (req.GET['path'], query_str), headers=headers) elif req.method == 'POST': conn.request("POST", req.GET['path'], req.body, headers=headers) # Handle the response and pull out the headers to proxy back resp = conn.getresponse() res = Response() for header, value in resp.getheaders(): if header.lower() in ['server', 'date']: continue res.headers[header] = value res.body = resp.read() return res relay.exposed=True def post_traceback(self, req): """Post the long XML traceback to the host and path provided""" debug_info = req.debug_info long_xml_er = formatter.format_xml(debug_info.exc_data, show_hidden_frames=True, show_extra_data=False, libraries=self.libraries)[0] host = req.GET['host'] headers = req.headers conn = httplib.HTTPConnection(host) headers = {'Content-Length':len(long_xml_er), 'Content-Type':'application/xml'} conn.request("POST", req.GET['path'], long_xml_er, headers=headers) resp = conn.getresponse() res = Response() for header, value in resp.getheaders(): if header.lower() in ['server', 'date']: continue res.headers[header] = value res.body = resp.read() return res post_traceback = get_debug_info(post_traceback) def media(self, req): """Static path where images and other files live""" first_part = req.path_info_peek() if first_part in self.media_paths: req.path_info_pop() path = self.media_paths[first_part] else: path = resource_filename("weberror", "eval-media") app = urlparser.StaticURLParser(path) return app media.exposed = True def summary(self, req): """ Returns a JSON-format summary of all the cached exception reports """ res = Response(content_type='text/x-json') data = []; items = self.debug_infos.values() items.sort(lambda a, b: cmp(a.created, b.created)) data = [item.json() for item in items] res.body = repr(data) return res summary.exposed = True def view(self, req): """ View old exception reports """ id = int(req.path_info_pop()) if id not in self.debug_infos: return exc.HTTPServerError( "Traceback by id %s does not exist (maybe " "the server has been restarted?)" % id) debug_info = self.debug_infos[id] return debug_info.wsgi_application view.exposed = True def make_view_url(self, environ, base_path, count): return base_path + '/view/%s' % count #@get_debug_info def show_frame(self, req): tbid = int(req.params['tbid']) frame = req.debug_info.frame(tbid) vars = frame.tb_frame.f_locals if vars: registry.restorer.restoration_begin(req.debug_info.counter) try: local_vars = make_table(vars) finally: registry.restorer.restoration_end() else: local_vars = 'No local vars' res = Response(content_type='text/html') res.body = input_form.substitute(tbid=tbid, debug_info=req.debug_info) + local_vars return res show_frame = get_debug_info(show_frame) #@get_debug_info def exec_input(self, req): input = req.params.get('input') if not input.strip(): return '' input = input.rstrip() + '\n' frame = req.debug_info.frame(int(req.params['tbid'])) vars = frame.tb_frame.f_locals glob_vars = frame.tb_frame.f_globals context = evalcontext.EvalContext(vars, glob_vars) registry.restorer.restoration_begin(req.debug_info.counter) try: output = context.exec_expr(input) finally: registry.restorer.restoration_end() input_html = formatter.str2html(input) res = Response(content_type='text/html') res.write( '>>> ' '%s
\n%s' % (preserve_whitespace(input_html, quote=False), preserve_whitespace(output))) return res exec_input = get_debug_info(exec_input) def source_code(self, req): location = req.params['location'] module_name, lineno = location.split(':', 1) module = sys.modules.get(module_name) if module is None: # Something weird indeed res = Response(content_type='text/html', charset='utf8') res.body = 'The module %s does not have an entry in sys.modules' % module_name return res filename = module.__file__ if filename[-4:] in ('.pyc', '.pyo'): filename = filename[:-1] elif filename.endswith('$py.class'): filename = '%s.py' % filename[:-9] f = open(filename, 'rb') source = f.read() f.close() html = ( ('
Module: %s file: %s
' '' % (module_name, filename, formatter.pygments_css)) + formatter.highlight(filename, source, linenos=True)) source_lines = len(source.splitlines()) if source_lines < 60: html += '\n
'*(60-source_lines) res = Response(content_type='text/html', charset='utf8') res.unicode_body = html return res source_code.exposed = True def respond(self, environ, start_response): req = Request(environ) if req.environ.get('paste.throw_errors'): return self.application(environ, start_response) base_path = req.application_url + '/_debug' req.environ['paste.throw_errors'] = True started = [] def detect_start_response(status, headers, exc_info=None): try: return start_response(status, headers, exc_info) except: raise else: started.append(True) try: __traceback_supplement__ = errormiddleware.Supplement, self, environ app_iter = self.application(environ, detect_start_response) # Don't create a list from a paste.fileapp object if isinstance(app_iter, fileapp._FileIter): return app_iter try: return_iter = list(app_iter) return return_iter finally: if hasattr(app_iter, 'close'): app_iter.close() except: exc_info = sys.exc_info() # Tell the Registry to save its StackedObjectProxies current state # for later restoration ## FIXME: needs to be more abstract (something in the environ) ## to remove the Paste dependency registry.restorer.save_registry_state(environ) count = get_debug_count(environ) view_uri = self.make_view_url(environ, base_path, count) if not started: headers = [('content-type', 'text/html')] headers.append(('X-Debug-URL', view_uri)) start_response('500 Internal Server Error', headers, exc_info) environ['wsgi.errors'].write('Debug at: %s\n' % view_uri) exc_data = collector.collect_exception(*exc_info) exc_data.view_url = view_uri if self.reporters: for reporter in self.reporters: reporter.report(exc_data) debug_info = DebugInfo(count, exc_info, exc_data, base_path, environ, view_uri, self.error_template, self.templating_formatters, self.head_html, self.footer_html, self.libraries) assert count not in self.debug_infos self.debug_infos[count] = debug_info if self.xmlhttp_key: if self.xmlhttp_key in req.params: exc_data = collector.collect_exception(*exc_info) html, extra_html = formatter.format_html( exc_data, include_hidden_frames=False, include_reusable=False, show_extra_data=False) return [html, extra_html] # @@: it would be nice to deal with bad content types here return debug_info.content() class DebugInfo(object): def __init__(self, counter, exc_info, exc_data, base_path, environ, view_uri, error_template, templating_formatters, head_html, footer_html, libraries): self.counter = counter self.exc_data = exc_data self.base_path = base_path self.environ = environ self.view_uri = view_uri self.error_template = error_template self.created = time.time() self.templating_formatters = templating_formatters self.head_html = head_html self.footer_html = footer_html self.libraries = libraries self.exc_type, self.exc_value, self.tb = exc_info __exception_formatter__ = 1 self.frames = [] n = 0 tb = self.tb while tb is not None and (limit is None or n < limit): if tb.tb_frame.f_locals.get('__exception_formatter__'): # Stop recursion. @@: should make a fake ExceptionFrame break self.frames.append(tb) tb = tb.tb_next n += 1 def json(self): """Return the JSON-able representation of this object""" return { 'uri': self.view_uri, 'created': time.strftime('%c', time.gmtime(self.created)), 'created_timestamp': self.created, 'exception_type': str(self.exc_type), 'exception': str(self.exc_value), } def frame(self, tbid): for frame in self.frames: if id(frame) == tbid: return frame else: raise ValueError, ( "No frame by id %s found from %r" % (tbid, self.frames)) def wsgi_application(self, environ, start_response): start_response('200 OK', [('content-type', 'text/html')]) return self.content() def content(self): traceback_body, extra_data = format_eval_html(self.exc_data, self.base_path, self.counter, self.libraries) repost_button = make_repost_button(self.environ) template_data = '

No Template information available.

' tab = 'traceback_data' for tmpl_formatter in self.templating_formatters: result = tmpl_formatter(self.exc_value) if result: tab = 'template_data' template_data = result break # Decode the exception value itself if needed formatted_exc_value = self.exc_data.exception_value if isinstance(formatted_exc_value, str): last_frame = self.exc_data.frames[-1] formatted_exc_value = formatted_exc_value.decode(last_frame.source_encoding, 'replace') formatted_exc_value = formatted_exc_value.encode('latin1', 'htmlentityreplace') formatted_exc_value = html_quote(formatted_exc_value) template_data = template_data.replace('

', '

') template_data = template_data.replace('

', '') if hasattr(self.exc_data.exception_type, '__name__'): exc_name = self.exc_data.exception_type.__name__ else: exc_name = str(self.exc_data.exception_type) page = self.error_template.substitute( head_html=self.head_html.substitute(prefix=self.base_path), pygments_css=formatter.pygments_css, footer_html=self.footer_html.substitute(prefix=self.base_path), repost_button=repost_button or '', traceback_body=traceback_body, exc_data=self.exc_data, exc_name=exc_name, formatted_exc_value=formatted_exc_value, extra_data=extra_data, template_data=template_data, set_tab=tab, prefix=self.base_path, counter=self.counter, ) return [page] class EvalHTMLFormatter(formatter.HTMLFormatter): def __init__(self, base_path, counter, **kw): super(EvalHTMLFormatter, self).__init__(**kw) self.base_path = base_path self.counter = counter def format_source_line(self, filename, frame): line = formatter.HTMLFormatter.format_source_line( self, filename, frame) location = '%s:%s' % (frame.modname, frame.lineno) return (line + '     ' '     ' 'view' % (frame.tbid, self.base_path, location)) def make_table(items): if hasattr(items, 'items'): items = items.items() items.sort() return table_template.substitute( html_quote=html_quote, items=items, preserve_whitespace=preserve_whitespace, make_wrappable=formatter.make_wrappable, pprint_format=pprint_format) table_template = HTMLTemplate(''' {{py:i = 0}} {{for name, value in items:}} {{py:i += 1}} {{py: value_html = html_quote(pprint_format(value, safe=True)) value_html = make_wrappable(value_html) if len(value_html) > 100: ## FIXME: This can break HTML; truncate before quoting? value_html, expand_html = value_html[:100], value_html[100:] else: expand_html = '' }} {{endfor}}
{{name}} {{preserve_whitespace(value_html, quote=False)|html}}{{if expand_html}} ... {{expand_html|html}} {{endif}}
''', name='table_template') def pprint_format(value, safe=False): out = StringIO() try: pprint.pprint(value, out) except Exception, e: if safe: out.write('Error: %s' % e) else: raise return out.getvalue() def format_eval_html(exc_data, base_path, counter, libraries): short_formatter = EvalHTMLFormatter( base_path=base_path, counter=counter, include_reusable=False) short_er, extra_data = short_formatter.format_collected_data(exc_data) short_text_er, text_extra_data = formatter.format_text(exc_data, show_extra_data=False) long_formatter = EvalHTMLFormatter( base_path=base_path, counter=counter, show_hidden_frames=True, show_extra_data=False, include_reusable=False) long_er, extra_data_none = long_formatter.format_collected_data(exc_data) long_text_er = formatter.format_text(exc_data, show_hidden_frames=True, show_extra_data=False)[0] long_xml_er = formatter.format_xml(exc_data, show_hidden_frames=True, show_extra_data=False, libraries=libraries)[0] short_xml_er = formatter.format_xml(exc_data, show_hidden_frames=False, show_extra_data=False, libraries=libraries)[0] if short_formatter.filter_frames(exc_data.frames) != \ long_formatter.filter_frames(exc_data.frames): # Only display the full traceback when it differs from the # short version long_text_er = cgi.escape(long_text_er) full_traceback_html = """
%s
""" % (long_er, len(long_text_er.splitlines()), long_text_er) else: full_traceback_html = '' short_text_er = cgi.escape(short_text_er) long_xml_leng = len(long_xml_er.splitlines()) if long_xml_leng > 50: long_xml_leng = 50 short_xml_leng = len(short_xml_er.splitlines()) if short_xml_leng > 50: short_xml_leng = 50 return """
%s
%s """ % (short_er, len(short_text_er.splitlines()), short_text_er, long_xml_leng, cgi.escape(long_xml_er), short_xml_leng, cgi.escape(short_xml_er), full_traceback_html), extra_data def make_repost_button(environ): url = request.construct_url(environ) if environ['REQUEST_METHOD'] == 'GET': return ('
' % url) else: # @@: I'd like to reconstruct this, but I can't because # the POST body is probably lost at this point, and # I can't get it back :( return None # @@: Use or lose the following code block """ fields = [] for name, value in request.parse_formvars( environ, include_get_vars=False).items(): if hasattr(value, 'filename'): # @@: Arg, we'll just submit the body, and leave out # the filename :( value = value.value fields.append( '' % (html_quote(name), html_quote(value))) return '''
%s
''' % (url, '\n'.join(fields)) """ input_form = HTMLTemplate('''

''', name='input_form') def make_eval_exception(app, global_conf, xmlhttp_key=None, reporters=None): """ Wraps the application in an interactive debugger. This debugger is a major security hole, and should only be used during development. xmlhttp_key is a string that, if present in QUERY_STRING, indicates that the request is an XMLHttp request, and the Javascript/interactive debugger should not be returned. (If you try to put the debugger somewhere with innerHTML, you will often crash the browser) """ if xmlhttp_key is None: xmlhttp_key = global_conf.get('xmlhttp_key', '_') if reporters is None: reporters = global_conf.get('error_reporters') if reporters and isinstance(reporters, basestring): reporter_strings = reporters.split() reporters = [] for reporter_string in reporter_strings: reporter = import_string.eval_import(reporter_string) if isinstance(reporter, (type, types.ClassType)): reporter = reporter() reporters.append(reporter) return EvalException(app, xmlhttp_key=xmlhttp_key, reporters=reporters) def make_general_exception(app, global_conf, interactive=False, **kw): """ Creates an error-catching middleware. If `interactive` is true then it will be the interactive exception catcher, otherwise it will be the static exception catcher. """ from paste.deploy.converters import asbool interactive = asbool(interactive) if interactive: return make_eval_exception(app, global_conf, **kw) else: from weberror.errormiddleware import make_error_middleware return make_error_middleware(app, global_conf, **kw) WebError-0.10.3+dfsg/weberror/util/0000775000000000000000000000000011466345335015557 5ustar rootrootWebError-0.10.3+dfsg/weberror/util/escaping.py0000664000000000000000000001712311016722455017717 0ustar rootroot# filters.py # Copyright (C) 2006, 2007, 2008 Geoffrey T. Dairiki # and Michael Bayer and Ben Bangert # # This module heavily based on the one from Mako and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php import re, cgi, urllib, htmlentitydefs, codecs from StringIO import StringIO xml_escapes = { '&' : '&', '>' : '>', '<' : '<', '"' : '"', # also " in html-only "'" : ''' # also ' in html-only } # XXX: " is valid in HTML and XML # ' is not valid HTML, but is valid XML def html_escape(string): return cgi.escape(string, True) def xml_escape(string): return re.sub(r'([&<"\'>])', lambda m: xml_escapes[m.group()], string) def url_escape(string): # convert into a list of octets string = string.encode("utf8") return urllib.quote_plus(string) def url_unescape(string): text = urllib.unquote_plus(string) if not is_ascii_str(text): text = text.decode("utf8") return text def trim(string): return string.strip() class Decode(object): def __getattr__(self, key): def decode(x): if isinstance(x, unicode): return x elif not isinstance(x, str): return unicode(str(x), encoding=key) else: return unicode(x, encoding=key) return decode decode = Decode() _ASCII_re = re.compile(r'\A[\x00-\x7f]*\Z') def is_ascii_str(text): return isinstance(text, str) and _ASCII_re.match(text) ################################################################ class XMLEntityEscaper(object): def __init__(self, codepoint2name, name2codepoint): self.codepoint2entity = dict([(c, u'&%s;' % n) for c,n in codepoint2name.iteritems()]) self.name2codepoint = name2codepoint def escape_entities(self, text): """Replace characters with their character entity references. Only characters corresponding to a named entity are replaced. """ return unicode(text).translate(self.codepoint2entity) def __escape(self, m): codepoint = ord(m.group()) try: return self.codepoint2entity[codepoint] except (KeyError, IndexError): return '&#x%X;' % codepoint __escapable = re.compile(r'["&<>]|[^\x00-\x7f]') def escape(self, text): """Replace characters with their character references. Replace characters by their named entity references. Non-ASCII characters, if they do not have a named entity reference, are replaced by numerical character references. The return value is guaranteed to be ASCII. """ return self.__escapable.sub(self.__escape, unicode(text) ).encode('ascii') # XXX: This regexp will not match all valid XML entity names__. # (It punts on details involving involving CombiningChars and Extenders.) # # .. __: http://www.w3.org/TR/2000/REC-xml-20001006#NT-EntityRef __characterrefs = re.compile(r'''& (?: \#(\d+) | \#x([\da-f]+) | ( (?!\d) [:\w] [-.:\w]+ ) ) ;''', re.X | re.UNICODE) def __unescape(self, m): dval, hval, name = m.groups() if dval: codepoint = int(dval) elif hval: codepoint = int(hval, 16) else: codepoint = self.name2codepoint.get(name, 0xfffd) # U+FFFD = "REPLACEMENT CHARACTER" if codepoint < 128: return chr(codepoint) return unichr(codepoint) def unescape(self, text): """Unescape character references. All character references (both entity references and numerical character references) are unescaped. """ return self.__characterrefs.sub(self.__unescape, text) _html_entities_escaper = XMLEntityEscaper(htmlentitydefs.codepoint2name, htmlentitydefs.name2codepoint) html_entities_escape = _html_entities_escaper.escape_entities html_entities_unescape = _html_entities_escaper.unescape def htmlentityreplace_errors(ex): """An encoding error handler. This python `codecs`_ error handler replaces unencodable characters with HTML entities, or, if no HTML entity exists for the character, XML character references. >>> u'The cost was \u20ac12.'.encode('latin1', 'htmlentityreplace') 'The cost was €12.' """ if isinstance(ex, UnicodeEncodeError): # Handle encoding errors bad_text = ex.object[ex.start:ex.end] text = _html_entities_escaper.escape(bad_text) return (unicode(text), ex.end) raise ex codecs.register_error('htmlentityreplace', htmlentityreplace_errors) # TODO: options to make this dynamic per-compilation will be added in a later release DEFAULT_ESCAPES = { 'x':'filters.xml_escape', 'h':'filters.html_escape', 'u':'filters.url_escape', 'trim':'filters.trim', 'entity':'filters.html_entities_escape', 'unicode':'unicode', 'decode':'decode', 'str':'str', 'n':'n' } # regexps used by _translateCdata(), # made global to compile once. # see http://www.xml.com/axml/target.html#dt-character ILLEGAL_LOW_CHARS = '[\x01-\x08\x0B-\x0C\x0E-\x1F]' ILLEGAL_HIGH_CHARS = '\xEF\xBF[\xBE\xBF]' # Note: Prolly fuzzy on this, but it looks as if characters from the # surrogate block are allowed if in scalar form, which is encoded in UTF8 the # same was as in surrogate block form XML_ILLEGAL_CHAR_PATTERN = re.compile( '%s|%s' % (ILLEGAL_LOW_CHARS, ILLEGAL_HIGH_CHARS)) # the characters that we will want to turn into entrefs # We must do so for &, <, and > following ]]. # The xml parser has more leeway, but we're not the parser. # http://www.xml.com/axml/target.html#dt-chardata # characters that we must *always* turn to entrefs: g_cdataCharPatternReq = re.compile('[&<]|]]>') g_charToEntityReq = { '&': '&', '<': '<', ']]>': ']]>', } # characters that we must turn to entrefs in attr values: g_cdataCharPattern = re.compile('[&<>"\']|]]>') g_charToEntity = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', ']]>': ']]>', } def removeIllegalChars(characters): if XML_ILLEGAL_CHAR_PATTERN.search(characters): characters = XML_ILLEGAL_CHAR_PATTERN.subn( lambda m: '&#%i;' % ord(m.group()), characters)[0] return characters def translateCdata(characters, allEntRefs = None): """Translate characters into a legal format.""" if not characters: return '' if allEntRefs: # translate all chars to entrefs; for attr value if g_cdataCharPattern.search(characters): new_string = g_cdataCharPattern.subn( lambda m, d=g_charToEntity: d[m.group()], characters)[0] else: new_string = characters else: # translate only required chars to entrefs if g_cdataCharPatternReq.search(characters): new_string = g_cdataCharPatternReq.subn( lambda m, d=g_charToEntityReq: d[m.group()], characters)[0] else: new_string = characters if XML_ILLEGAL_CHAR_PATTERN.search(new_string): new_string = XML_ILLEGAL_CHAR_PATTERN.subn( lambda m: '&#%i;' % ord(m.group()), new_string)[0] return new_string WebError-0.10.3+dfsg/weberror/util/serial_number_generator.py0000664000000000000000000000762011070224122023010 0ustar rootroot# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org) # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php """ Creates a human-readable identifier, using numbers and digits, avoiding ambiguous numbers and letters. hash_identifier can be used to create compact representations that are unique for a certain string (or concatenation of strings) """ try: from hashlib import md5 except ImportError: from md5 import md5 good_characters = "23456789abcdefghjkmnpqrtuvwxyz" base = len(good_characters) def make_identifier(number): """ Encodes a number as an identifier. """ if not isinstance(number, (int, long)): raise ValueError( "You can only make identifiers out of integers (not %r)" % number) if number < 0: raise ValueError( "You cannot make identifiers out of negative numbers: %r" % number) result = [] while number: next = number % base result.append(good_characters[next]) # Note, this depends on integer rounding of results: number = number / base return ''.join(result) def hash_identifier(s, length, pad=True, hasher=md5, prefix='', group=None, upper=False): """ Hashes the string (with the given hashing module), then turns that hash into an identifier of the given length (using modulo to reduce the length of the identifier). If ``pad`` is False, then the minimum-length identifier will be used; otherwise the identifier will be padded with 0's as necessary. ``prefix`` will be added last, and does not count towards the target length. ``group`` will group the characters with ``-`` in the given lengths, and also does not count towards the target length. E.g., ``group=4`` will cause a identifier like ``a5f3-hgk3-asdf``. Grouping occurs before the prefix. """ if not callable(hasher): # Accept sha/md5 modules as well as callables hasher = hasher.new if length > 26 and hasher is md5: raise ValueError, ( "md5 cannot create hashes longer than 26 characters in " "length (you gave %s)" % length) if isinstance(s, unicode): s = s.encode('utf-8') h = hasher(str(s)) bin_hash = h.digest() modulo = base ** length number = 0 for c in list(bin_hash): number = (number * 256 + ord(c)) % modulo ident = make_identifier(number) if pad: ident = good_characters[0]*(length-len(ident)) + ident if group: parts = [] while ident: parts.insert(0, ident[-group:]) ident = ident[:-group] ident = '-'.join(parts) if upper: ident = ident.upper() return prefix + ident # doctest tests: __test__ = { 'make_identifier': """ >>> make_identifier(0) '' >>> make_identifier(1000) 'c53' >>> make_identifier(-100) Traceback (most recent call last): ... ValueError: You cannot make identifiers out of negative numbers: -100 >>> make_identifier('test') Traceback (most recent call last): ... ValueError: You can only make identifiers out of integers (not 'test') >>> make_identifier(1000000000000) 'c53x9rqh3' """, 'hash_identifier': """ >>> hash_identifier(0, 5) 'cy2dr' >>> hash_identifier(0, 10) 'cy2dr6rg46' >>> hash_identifier('this is a test of a long string', 5) 'awatu' >>> hash_identifier(0, 26) 'cy2dr6rg46cx8t4w2f3nfexzk4' >>> hash_identifier(0, 30) Traceback (most recent call last): ... ValueError: md5 cannot create hashes longer than 26 characters in length (you gave 30) >>> hash_identifier(0, 10, group=4) 'cy-2dr6-rg46' >>> hash_identifier(0, 10, group=4, upper=True, prefix='M-') 'M-CY-2DR6-RG46' """} if __name__ == '__main__': import doctest doctest.testmod() WebError-0.10.3+dfsg/weberror/util/source_encoding.py0000664000000000000000000000315611010417022021256 0ustar rootroot"""Parse a Python source code encoding string""" import codecs import re # Regexp to match python magic encoding line PYTHON_MAGIC_COMMENT_re = re.compile( r'[ \t\f]* \# .* coding[=:][ \t]*([-\w.]+)', re.VERBOSE) def parse_encoding(lines): """Deduce the encoding of a source file from magic comment. It does this in the same way as the `Python interpreter`__ .. __: http://docs.python.org/ref/encodings.html The ``lines`` argument should be a list of the first 2 lines of the source code. (From Jeff Dairiki) """ try: line1 = lines[0] has_bom = line1.startswith(codecs.BOM_UTF8) if has_bom: line1 = line1[len(codecs.BOM_UTF8):] m = PYTHON_MAGIC_COMMENT_re.match(line1) if not m: try: import parser parser.suite(line1) except (ImportError, SyntaxError): # Either it's a real syntax error, in which case the source is # not valid python source, or line2 is a continuation of line1, # in which case we don't want to scan line2 for a magic # comment. pass else: line2 = lines[1] m = PYTHON_MAGIC_COMMENT_re.match(line2) if has_bom: if m: raise SyntaxError( "python refuses to compile code with both a UTF8 " "byte-order-mark and a magic encoding comment") return 'utf_8' elif m: return m.group(1) else: return None except: return None WebError-0.10.3+dfsg/weberror/util/errorapp.py0000644000000000000000000000046210727022360017750 0ustar rootroot""" This simple application creates errors """ def error_app(environ, start_response): environ['errorapp.item'] = 1 raise_error() def raise_error(): if 1 == 1: raise Exception('This is an exception') else: do_stuff() def make_error_app(global_conf): return error_app WebError-0.10.3+dfsg/weberror/util/__init__.py0000644000000000000000000000000010723213331017635 0ustar rootrootWebError-0.10.3+dfsg/weberror/__init__.py0000644000000000000000000000000210723213331016662 0ustar rootroot# WebError-0.10.3+dfsg/weberror/collector.py0000664000000000000000000004744311466344242017152 0ustar rootroot# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org) # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php ############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## ## Originally zExceptions.ExceptionFormatter from Zope; ## Modified by Ian Bicking, Imaginary Landscape, 2005 """ An exception collector that finds traceback information plus supplements """ import sys import traceback import time try: from cStringIO import StringIO except ImportError: from StringIO import StringIO import linecache from weberror.util import source_encoding, serial_number_generator DEBUG_EXCEPTION_FORMATTER = True DEBUG_IDENT_PREFIX = 'E-' FALLBACK_ENCODING = 'UTF-8' __all__ = ['collect_exception', 'ExceptionCollector'] class ExceptionCollector(object): """ Produces a data structure that can be used by formatters to display exception reports. Magic variables: If you define one of these variables in your local scope, you can add information to tracebacks that happen in that context. This allows applications to add all sorts of extra information about the context of the error, including URLs, environmental variables, users, hostnames, etc. These are the variables we look for: ``__traceback_supplement__``: You can define this locally or globally (unlike all the other variables, which must be defined locally). ``__traceback_supplement__`` is a tuple of ``(factory, arg1, arg2...)``. When there is an exception, ``factory(arg1, arg2, ...)`` is called, and the resulting object is inspected for supplemental information. ``__traceback_info__``: This information is added to the traceback, usually fairly literally. ``__traceback_hide__``: If set and true, this indicates that the frame should be hidden from abbreviated tracebacks. This way you can hide some of the complexity of the larger framework and let the user focus on their own errors. By setting it to ``'before'``, all frames before this one will be thrown away. By setting it to ``'after'`` then all frames after this will be thrown away until ``'reset'`` is found. In each case the frame where it is set is included, unless you append ``'_and_this'`` to the value (e.g., ``'before_and_this'``). Note that formatters will ignore this entirely if the frame that contains the error wouldn't normally be shown according to these rules. ``__traceback_reporter__``: This should be a reporter object (see the reporter module), or a list/tuple of reporter objects. All reporters found this way will be given the exception, innermost first. ``__traceback_decorator__``: This object (defined in a local or global scope) will get the result of this function (the CollectedException defined below). It may modify this object in place, or return an entirely new object. This gives the object the ability to manipulate the traceback arbitrarily. The actually interpretation of these values is largely up to the reporters and formatters. ``collect_exception(*sys.exc_info())`` will return an object with several attributes: ``frames``: A list of frames ``exception_formatted``: The formatted exception, generally a full traceback ``exception_type``: The type of the exception, like ``ValueError`` ``exception_value``: The string value of the exception, like ``'x not in list'`` ``identification_code``: A hash of the exception data meant to identify the general exception, so that it shares this code with other exceptions that derive from the same problem. The code is a hash of all the module names and function names in the traceback, plus exception_type. This should be shown to users so they can refer to the exception later. (@@: should it include a portion that allows identification of the specific instance of the exception as well?) The list of frames goes innermost first. Each frame has these attributes; some values may be None if they could not be determined. ``modname``: the name of the module ``filename``: the filename of the module ``lineno``: the line of the error ``revision``: the contents of __version__ or __revision__ ``name``: the function name ``supplement``: an object created from ``__traceback_supplement__`` ``supplement_exception``: a simple traceback of any exception ``__traceback_supplement__`` created ``traceback_info``: the str() of any ``__traceback_info__`` variable found in the local scope (@@: should it str()-ify it or not?) ``traceback_hide``: the value of any ``__traceback_hide__`` variable ``traceback_log``: the value of any ``__traceback_log__`` variable ``__traceback_supplement__`` is thrown away, but a fixed set of attributes are captured; each of these attributes is optional. ``object``: the name of the object being visited ``source_url``: the original URL requested ``line``: the line of source being executed (for interpreters, like ZPT) ``column``: the column of source being executed ``expression``: the expression being evaluated (also for interpreters) ``warnings``: a list of (string) warnings to be displayed ``getInfo``: a function/method that takes no arguments, and returns a string describing any extra information ``extraData``: a function/method that takes no arguments, and returns a dictionary. The contents of this dictionary will not be displayed in the context of the traceback, but globally for the exception. Results will be grouped by the keys in the dictionaries (which also serve as titles). The keys can also be tuples of (importance, title); in this case the importance should be ``important`` (shows up at top), ``normal`` (shows up somewhere; unspecified), ``supplemental`` (shows up at bottom), or ``extra`` (shows up hidden or not at all). These are used to create an object with attributes of the same names (``getInfo`` becomes a string attribute, not a method). ``__traceback_supplement__`` implementations should be careful to produce values that are relatively static and unlikely to cause further errors in the reporting system -- any complex introspection should go in ``getInfo()`` and should ultimately return a string. Note that all attributes are optional, and under certain circumstances may be None or may not exist at all -- the collector can only do a best effort, but must avoid creating any exceptions itself. Formatters may want to use ``__traceback_hide__`` as a hint to hide frames that are part of the 'framework' or underlying system. There are a variety of rules about special values for this variables that formatters should be aware of. TODO: More attributes in __traceback_supplement__? Maybe an attribute that gives a list of local variables that should also be collected? Also, attributes that would be explicitly meant for the entire request, not just a single frame. Right now some of the fixed set of attributes (e.g., source_url) are meant for this use, but there's no explicit way for the supplement to indicate new values, e.g., logged-in user, HTTP referrer, environment, etc. Also, the attributes that do exist are Zope/Web oriented. More information on frames? cgitb, for instance, produces extensive information on local variables. There exists the possibility that getting this information may cause side effects, which can make debugging more difficult; but it also provides fodder for post-mortem debugging. However, the collector is not meant to be configurable, but to capture everything it can and let the formatters be configurable. Maybe this would have to be a configuration value, or maybe it could be indicated by another magical variable (which would probably mean 'show all local variables below this frame') """ show_revisions = 0 def __init__(self, limit=None): self.limit = limit def getLimit(self): limit = self.limit if limit is None: limit = getattr(sys, 'tracebacklimit', None) return limit def getRevision(self, globals): if not self.show_revisions: return None revision = globals.get('__revision__', None) if revision is None: # Incorrect but commonly used spelling revision = globals.get('__version__', None) if revision is not None: try: revision = str(revision).strip() except: revision = '???' return revision def collectSupplement(self, supplement, tb): result = {} for name in ('object', 'source_url', 'line', 'column', 'expression', 'warnings'): result[name] = getattr(supplement, name, None) func = getattr(supplement, 'getInfo', None) if func: result['info'] = func() else: result['info'] = None func = getattr(supplement, 'extraData', None) if func: result['extra'] = func() else: result['extra'] = None return SupplementaryData(**result) def collectLine(self, tb, extra_data): f = tb.tb_frame lineno = tb.tb_lineno co = f.f_code filename = co.co_filename name = co.co_name locals = f.f_locals globals = f.f_globals data = {} data['modname'] = globals.get('__name__', None) data['filename'] = filename data['lineno'] = lineno data['revision'] = self.getRevision(globals) data['name'] = name data['tbid'] = id(tb) data['locals'] = locals # Output a traceback supplement, if any. if '__traceback_supplement__' in locals: # Use the supplement defined in the function. tbs = locals['__traceback_supplement__'] elif globals.has_key('__traceback_supplement__'): # Use the supplement defined in the module. # This is used by Scripts (Python). tbs = globals['__traceback_supplement__'] else: tbs = None if tbs is not None: factory = tbs[0] args = tbs[1:] try: supp = factory(*args) data['supplement'] = self.collectSupplement(supp, tb) if data['supplement'].extra: for key, value in data['supplement'].extra.items(): extra_data.setdefault(key, []).append(value) except: if DEBUG_EXCEPTION_FORMATTER: out = StringIO() traceback.print_exc(file=out) text = out.getvalue() data['supplement_exception'] = text # else just swallow the exception. try: tbi = locals.get('__traceback_info__', None) if tbi is not None: data['traceback_info'] = str(tbi) except: pass marker = [] for name in ('__traceback_hide__', '__traceback_log__', '__traceback_decorator__'): try: tbh = locals.get(name, globals.get(name, marker)) if tbh is not marker: data[name[2:-2]] = tbh except: pass return data def collectExceptionOnly(self, etype, value): return traceback.format_exception_only(etype, value) def collectException(self, etype, value, tb, limit=None): # The next line provides a way to detect recursion. __exception_formatter__ = 1 frames = [] ident_data = [] traceback_decorators = [] if limit is None: limit = self.getLimit() n = 0 extra_data = {} while tb is not None and (limit is None or n < limit): if tb.tb_frame.f_locals.get('__exception_formatter__'): # Stop recursion. @@: should make a fake ExceptionFrame frames.append('(Recursive formatException() stopped)\n') break data = self.collectLine(tb, extra_data) frame = ExceptionFrame(**data) frames.append(frame) if frame.traceback_decorator is not None: traceback_decorators.append(frame.traceback_decorator) ident_data.append(frame.modname or '?') ident_data.append(frame.name or '?') tb = tb.tb_next n = n + 1 ident_data.append(str(etype)) ident = serial_number_generator.hash_identifier( ' '.join(ident_data), length=5, upper=True, prefix=DEBUG_IDENT_PREFIX) result = CollectedException( frames=frames, exception_formatted=self.collectExceptionOnly(etype, value), exception_type=etype, exception_value=self.safeStr(value), identification_code=ident, date=time.localtime(), extra_data=extra_data) if etype is ImportError: extra_data[('important', 'sys.path')] = [sys.path] for decorator in traceback_decorators: try: new_result = decorator(result) if new_result is not None: result = new_result except: pass return result def safeStr(self, obj): try: return str(obj) except UnicodeEncodeError: try: return unicode(obj).encode(FALLBACK_ENCODING, 'replace') except UnicodeEncodeError: # This is when something is really messed up, but this can # happen when the __str__ of an object has to handle unicode return repr(obj) except: try: extra = ' (exception showing exception: %s)' % str(sys.exc_info()[1]) except: extra = '' return repr(obj) + extra limit = 200 class Bunch(object): """ A generic container """ def __init__(self, **attrs): for name, value in attrs.items(): setattr(self, name, value) def __repr__(self): name = '<%s ' % self.__class__.__name__ try: name += ' '.join(['%s=%r' % (name, str(value)[:30]) for name, value in self.__dict__.items() if not name.startswith('_')]) except: name += ' UNABLE TO GET REPRESENTATION' return name + '>' class CollectedException(Bunch): """ This is the result of collection the exception; it contains copies of data of interest. """ # A list of frames (ExceptionFrame instances), innermost last: frames = [] # The result of traceback.format_exception_only; this looks # like a normal traceback you'd see in the interactive interpreter exception_formatted = None # The *string* representation of the type of the exception # (@@: should we give the # actual class? -- we can't keep the # actual exception around, but the class should be safe) # Something like 'ValueError' exception_type = None # The string representation of the exception, from ``str(e)``. exception_value = None # An identifier which should more-or-less classify this particular # exception, including where in the code it happened. identification_code = None # The date, as time.localtime() returns: date = None # A dictionary of supplemental data: extra_data = {} class SupplementaryData(Bunch): """ The result of __traceback_supplement__. We don't keep the supplement object around, for fear of GC problems and whatnot. (@@: Maybe I'm being too superstitious about copying only specific information over) """ # These attributes are copied from the object, or left as None # if the object doesn't have these attributes: object = None source_url = None line = None column = None expression = None warnings = None # This is the *return value* of supplement.getInfo(): info = None class ExceptionFrame(Bunch): """ This represents one frame of the exception. Each frame is a context in the call stack, typically represented by a line number and module name in the traceback. """ # The name of the module; can be None, especially when the code # isn't associated with a module. modname = None # The filename (@@: when no filename, is it None or '?'?) filename = None # Line number lineno = None # The value of __revision__ or __version__ -- but only if # show_revision = True (by defaut it is false). (@@: Why not # collect this?) revision = None # The name of the function with the error (@@: None or '?' when # unknown?) name = None # A SupplementaryData object, if __traceback_supplement__ was found # (and produced no errors) supplement = None # If accessing __traceback_supplement__ causes any error, the # plain-text traceback is stored here supplement_exception = None # The str() of any __traceback_info__ value found traceback_info = None # The value of __traceback_hide__ traceback_hide = False # The value of __traceback_decorator__ traceback_decorator = None # The id() of the traceback scope, can be used to reference the # scope for use elsewhere tbid = None # The filename's source code encoding _source_encoding = None def get_source_line(self, context=0): """ Return the source of the current line of this frame. You probably want to .strip() it as well, as it is likely to have leading whitespace. If context is given, then that many lines on either side will also be returned. E.g., context=1 will give 3 lines. """ if not self.filename or not self.lineno: return None lines = [] for lineno in range(self.lineno-context, self.lineno+context+1): lines.append(linecache.getline(self.filename, lineno)) return ''.join(lines) def _get_source_encoding(self): if self._source_encoding: return self._source_encoding lines = [linecache.getline(self.filename, 1), linecache.getline(self.filename, 2)] self._source_encoding = \ source_encoding.parse_encoding(lines) or 'ascii' return self._source_encoding source_encoding = property(_get_source_encoding) if hasattr(sys, 'tracebacklimit'): limit = min(limit, sys.tracebacklimit) col = ExceptionCollector() def collect_exception(t, v, tb, limit=None): """ Collection an exception from ``sys.exc_info()``. Use like:: try: blah blah except: exc_data = collect_exception(*sys.exc_info()) """ return col.collectException(t, v, tb, limit=limit) WebError-0.10.3+dfsg/weberror/pdbcapture.py0000664000000000000000000001161611466344257017314 0ustar rootrootfrom webob import Request, Response import threading from paste.util import threadedprint from itertools import count import tempita from paste.urlparser import StaticURLParser from paste.util.filemixin import FileMixin import os import sys try: import json except ImportError: # pragma: no cover import simplejson as json here = os.path.dirname(os.path.abspath(__file__)) #def debug(msg, *args): # args = '%s %s' % (msg, ' '.join(map(repr, args))) # print >> sys.stderr, args class PdbCapture(object): def __init__(self, app): self.app = app threadedprint.install(leave_stdout=True) threadedprint.install_stdin() self.counter = count() self.static_app = StaticURLParser(os.path.join(here, 'pdbcapture/static')) self.media_app = StaticURLParser(os.path.join(here, 'eval-media')) self.states = {} def get_template(self, template_name): filename = os.path.join(os.path.dirname(__file__), template_name) return tempita.HTMLTemplate.from_filename(filename) def __call__(self, environ, start_response): req = Request(environ) if req.GET.get('__pdbid__'): id = int(req.GET['__pdbid__']) response = self.states[id]['response'] return response(environ, start_response) if req.path_info_peek() == '.pdbcapture': req.path_info_pop() if req.path_info_peek() == 'static': req.path_info_pop() return self.static_app(environ, start_response) if req.path_info_peek() == 'media': req.path_info_pop() return self.media_app(environ, start_response) resp = self.internal_request(req) return resp(environ, start_response) id = self.counter.next() state = dict(id=id, event=threading.Event(), base_url=req.application_url, stdout=[], stdin=[], stdin_event=threading.Event()) t = threading.Thread(target=self.call_app, args=(req, state)) t.setDaemon(True) t.start() state['event'].wait() if 'response' in state: # Normal request, nothing happened resp = state['response'] return resp(environ, start_response) if 'exc_info' in state: raise state['exc_info'][0], state['exc_info'][1], state['exc_info'][2] self.states[id] = state tmpl = self.get_template('pdbcapture_response.html') body = tmpl.substitute(req=req, state=state, id=id) resp = Response(body) return resp(environ, start_response) def internal_request(self, req): id = int(req.params['id']) state = self.states[id] if 'response' in state: body = {'response': 1} else: if req.params.get('stdin'): state['stdin'].append(req.params['stdin']) state['stdin_event'].set() stdout = ''.join(state['stdout']) state['stdout'][:] = [] body = {'stdout': stdout} if not state['stdin_event'].isSet(): body['stdinPending'] = 1 resp = Response(content_type='application/json', body=json.dumps(body)) return resp def call_app(self, req, state): event = state['event'] stream_handler = StreamHandler(stdin=state['stdin'], stdin_event=state['stdin_event'], stdout=state['stdout'], signal_event=state['event']) threadedprint.register(stream_handler) threadedprint.register_stdin(stream_handler) try: resp = req.get_response(self.app) state['response'] = resp except: state['exc_info'] = sys.exc_info() event.set() class StreamHandler(FileMixin): def __init__(self, stdin, stdout, stdin_event, signal_event): self.stdin = stdin self.stdout = stdout self.stdin_event = stdin_event self.signal_event = signal_event def write(self, text): self.stdout.append(text) def read(self, size=None): self.signal_event.set() text = ''.join(self.stdin) if size is None or size == -1: self.stdin[:] = [] sys.stdout.write(text) return text while len(text) < size: self.stdin_event.clear() self.stdin_event.wait() text = ''.join(self.stdin) pending = text[:size] self.stdin[:] = [text[size:]] sys.stdout.write(pending) return pending def test_app(environ, start_response): import pdb message = "Hey, what's up?" pdb.set_trace() start_response('200 OK', [('Content-type', 'text/plain')]) return [message] if __name__ == '__main__': from paste import httpserver httpserver.serve(PdbCapture(test_app)) WebError-0.10.3+dfsg/weberror/exceptions/0000775000000000000000000000000011466345335016763 5ustar rootrootWebError-0.10.3+dfsg/weberror/exceptions/errormiddleware.py0000664000000000000000000000124311003173153022504 0ustar rootrootimport warnings def ErrorMiddleware(*args, **kw): warnings.warn( 'weberror.exceptions.errormiddleware.ErrorMiddleware has been moved ' 'to weberror.errormiddleware.ErrorMiddleware', DeprecationWarning, stacklevel=2) from weberror.errormiddleware import ErrorMiddleware return ErrorMiddleware(*args, **kw) def handle_exception(*args, **kw): warnings.warn( 'weberror.exceptions.errormiddleware.handle_exception has been moved ' 'to weberror.errormiddleware.handle_exception', DeprecationWarning, stacklevel=2) from weberror.errormiddleware import handle_exceptions return handle_exceptions(*args, **kw) WebError-0.10.3+dfsg/weberror/exceptions/__init__.py0000644000000000000000000000000210770066101021046 0ustar rootroot# WebError-0.10.3+dfsg/weberror/reporter.py0000664000000000000000000001153111335430006017000 0ustar rootroot# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org) # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php from email.MIMEText import MIMEText from email.MIMEMultipart import MIMEMultipart import smtplib import time from weberror import formatter class Reporter(object): def __init__(self, **conf): for name, value in conf.items(): if not hasattr(self, name): raise TypeError( "The keyword argument %s was not expected" % name) setattr(self, name, value) self.check_params() def check_params(self): pass def format_date(self, exc_data): return time.strftime('%c', exc_data.date) def format_html(self, exc_data, **kw): return formatter.format_html(exc_data, **kw) def format_text(self, exc_data, **kw): return formatter.format_text(exc_data, **kw) class EmailReporter(Reporter): to_addresses = None from_address = None smtp_server = 'localhost' smtp_username = None smtp_password = None smtp_use_tls = False subject_prefix = '' def report(self, exc_data): msg = self.assemble_email(exc_data) server = smtplib.SMTP(self.smtp_server) if self.smtp_use_tls: server.ehlo() server.starttls() server.ehlo() if self.smtp_username and self.smtp_password: server.login(self.smtp_username, self.smtp_password) ## FIXME: this should check the return value from this function: result = server.sendmail(self.from_address, self.to_addresses, msg.as_string()) try: server.quit() except sslerror: # sslerror is raised in tls connections on closing sometimes pass def check_params(self): if not self.to_addresses: raise ValueError("You must set to_addresses") if not self.from_address: raise ValueError("You must set from_address") if isinstance(self.to_addresses, (str, unicode)): self.to_addresses = [self.to_addresses] def assemble_email(self, exc_data): short_html_version, short_extra = self.format_html( exc_data, show_hidden_frames=False, show_extra_data=True) long_html_version, long_extra = self.format_html( exc_data, show_hidden_frames=True, show_extra_data=True) text_version = self.format_text( exc_data, show_hidden_frames=True, show_extra_data=True)[0] msg = MIMEMultipart() msg.set_type('multipart/alternative') msg.preamble = msg.epilogue = '' text_msg = MIMEText(as_str(text_version)) text_msg.set_type('text/plain') text_msg.set_param('charset', 'UTF-8') msg.attach(text_msg) html_msg = MIMEText(as_str(short_html_version) + as_str(''.join(short_extra))) html_msg.set_type('text/html') html_msg.set_param('charset', 'UTF-8') html_long = MIMEText(as_str(long_html_version) + as_str(''.join(long_extra))) html_long.set_type('text/html') html_long.set_param('charset', 'UTF-8') msg.attach(html_msg) msg.attach(html_long) subject = as_str('%s: %s' % (exc_data.exception_type, formatter.truncate(str(exc_data.exception_value)))) msg['Subject'] = as_str(self.subject_prefix) + subject msg['From'] = as_str(self.from_address) msg['To'] = as_str(', '.join(self.to_addresses)) return msg class LogReporter(Reporter): filename = None show_hidden_frames = True def check_params(self): assert self.filename is not None, ( "You must give a filename") def report(self, exc_data): text, head_text = self.format_text( exc_data, show_hidden_frames=self.show_hidden_frames) f = open(self.filename, 'a') try: f.write(text + '\n' + '-'*60 + '\n') finally: f.close() class FileReporter(Reporter): file = None show_hidden_frames = True def check_params(self): assert self.file is not None, ( "You must give a file object") def report(self, exc_data): text = self.format_text( exc_data, show_hidden_frames=self.show_hidden_frames) self.file.write(text + '\n' + '-'*60 + '\n') class WSGIAppReporter(Reporter): def __init__(self, exc_data): self.exc_data = exc_data def __call__(self, environ, start_response): start_response('500 Server Error', [('Content-type', 'text/html')]) return [formatter.format_html(self.exc_data)] def as_str(v): if isinstance(v, str): return v if not isinstance(v, unicode): v = unicode(v) if isinstance(v, unicode): v = v.encode('utf8') return v WebError-0.10.3+dfsg/README0000644000000000000000000000000010723213331013600 0ustar rootrootWebError-0.10.3+dfsg/LICENSE0000644000000000000000000000427711012136673013756 0ustar rootrootEXCEPT FOR JQUERY, ALL CODE IS LICENSED AS FOLLOWS: Copyright (c) 2008 Ben Bangert, Ian Bicking Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. JQUERY IS LICENSED UNDER THE MIT LICENSE: Copyright (c) 2008 John Resig, http://jquery.com/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. WebError-0.10.3+dfsg/MANIFEST.in0000664000000000000000000000012611003174504014471 0ustar rootrootrecursive-include weberror/eval-media * recursive-include weberror eval_template.html WebError-0.10.3+dfsg/.hgtags0000664000000000000000000000073511335430037014223 0ustar rootroot641409089c70fa587f9535f2752eb0424dbf9d65 v0.8a 2812e5d66cbbdeb54594d46a0da768459038bcfa v0.8 018397c549de6366aebd1c2a4ddd809997e14ef2 v0.9 4abb0b1bcb8d95efe79de71c96002b580582560e v0.9.1 02d8a5923a5c899bee2464af450ac0f1268b5e20 v0.10 a7942bc0fd124522de37c1f33e11e2463afaeb0e v0.10 b78d1b83347b515a9b838b4e88756baa8d67e68b v0.10.1 602a4d02080667d9a7adf9830140d75e64e54c36 v0.10.2 602a4d02080667d9a7adf9830140d75e64e54c36 v0.10.2 19525cc8a25c6beb9dda23fb893b303af033cceb v0.10.2 WebError-0.10.3+dfsg/CHANGELOG0000664000000000000000000000235511466345271014171 0ustar rootrootWebError Changelog ================== 0.10.3 (11/9/2010) * Don't require simplejson on Python 2.6 0.10.2 (2/12/2010) * Fix bug when displaying UTF-8 type errors. * Fix bug when emailing data with UTF-8. 0.10.1 (12/29/2008) * Fix view source when __file__ is .pyo or $py.class. 0.10 (12/18/2008) * Fix indentation of code lines in the traceback view. * Enable syntax highlighting in view source. * Fix a case where the response could become unicode; fix the docstring patching when using python -O 0.9.1 (10/28/2008) * Python 2.6 compatibility * Making main page links more accessible to browsers with no JS on per Pylons Trac ticket #489. 0.9 (07/08/2008) * Switched to using Pygments for highlighting. * Added better handling of exceptions that don't cleanly convert to str(). * Added dependency library listings for XML output. 0.8 (06/12/2008) * Added fairly basic pdbcapture system. * Fixed errors in unicode handling and exception displaying. * Updated JS to use jQuery where applicable. Updated jQuery lib and added jQuery hotkeys plugin. * Refactored to a flatter layout. 0.8a (02/27/2008) * Fixed error in email due to restructuring of project. * Added xml formattor output. * Added try/except in case an objects repr throws an exception. WebError-0.10.3+dfsg/PKG-INFO0000664000000000000000000000144511466345335014054 0ustar rootrootMetadata-Version: 1.0 Name: WebError Version: 0.10.3 Summary: Web Error handling and exception catching Home-page: UNKNOWN Author: Ben Bangert, Ian Bicking, Mark Ramm Author-email: UNKNOWN License: MIT Description: UNKNOWN Keywords: wsgi Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Programming Language :: Python Classifier: Topic :: Internet :: WWW/HTTP Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Topic :: Internet :: WWW/HTTP :: WSGI Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Application Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware WebError-0.10.3+dfsg/setup.py0000664000000000000000000000325411466345133014465 0ustar rootrootfrom setuptools import setup, find_packages import sys version = '0.10.3' install_requires = [ 'WebOb', 'Tempita', 'Pygments', 'Paste>=1.7.1', ] if sys.version_info[:2] < (2, 6): install_requires.append('simplejson') setup(name='WebError', version=version, description="Web Error handling and exception catching", long_description="""\ """, classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Topic :: Internet :: WWW/HTTP", "Topic :: Internet :: WWW/HTTP :: Dynamic Content", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Internet :: WWW/HTTP :: WSGI", "Topic :: Internet :: WWW/HTTP :: WSGI :: Application", "Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware", ], keywords='wsgi', author='Ben Bangert, Ian Bicking, Mark Ramm', author_email='', url='', license='MIT', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, package_data = { 'weberror.evalexception': [ "*.html.tmpl", "media/*" ] }, zip_safe=False, install_requires=install_requires, test_suite='nose.collector', tests_require=['nose', 'webtest', 'Paste'], entry_points=""" [paste.filter_app_factory] main = weberror.evalexception:make_general_exception error_catcher = weberror.errormiddleware:make_error_middleware evalerror = weberror.evalexception:make_eval_exception """, ) WebError-0.10.3+dfsg/tests/0000775000000000000000000000000011466345335014115 5ustar rootrootWebError-0.10.3+dfsg/tests/reporter_output/0000775000000000000000000000000011466345335017377 5ustar rootrootWebError-0.10.3+dfsg/tests/reporter_output/.testdir0000644000000000000000000000000010723213331021023 0ustar rootrootWebError-0.10.3+dfsg/tests/test_config.ini0000644000000000000000000000031410727022360017103 0ustar rootroot[filter-app:main] use = egg:WebError#evalerror next = error-app [app:error-app] paste.app_factory = weberror.util.errorapp:make_error_app [server:main] use = egg:Paste#http host = 127.0.0.1 port = 8080 WebError-0.10.3+dfsg/tests/__init__.py0000644000000000000000000000000210723213331016175 0ustar rootroot# WebError-0.10.3+dfsg/tests/evaldemo.py0000664000000000000000000000473011032256447016261 0ustar rootrootfrom weberror.evalexception import EvalException def error_application(environ, start_response): a = 1 b = 'x'*1000 return sub_application(environ, start_response) def sub_application(environ, start_response): test = 10 raise Exception('The expected ') if __name__ == '__main__': import optparse parser = optparse.OptionParser() parser.add_option('--port', default='8080', help='The port to serve on (default 8080)', dest='port') parser.add_option('--no-eval', action='store_true', dest='no_eval', help='Don\'t use the eval catcher, just the static catcher') parser.add_option('--email', metavar='EMAIL', help='Use the emailer instead of evalexception', dest='email') parser.add_option('--email-from', metavar='EMAIL', help='Send the email as FROM this account', dest='email_from') parser.add_option('--smtp-server', default='localhost', metavar='HOST[:PORT]', dest='smtp_server', help='SMTP server to use') parser.add_option('--smtp-username', metavar='USERNAME', dest='smtp_username', help='SMTP username') parser.add_option('--smtp-password', metavar='PASSWORD', dest='smtp_password', help='SMTP password') parser.add_option('--smtp-use-tls', dest='smtp_use_tls', action='store_true', help='Use TLS (SSL) for SMTP server') options, args = parser.parse_args() from paste.httpserver import serve if options.no_eval or options.email: from weberror.errormiddleware import ErrorMiddleware if not options.email_from: options.email_from = options.email app = ErrorMiddleware( error_application, debug=True, error_email=options.email, smtp_server=options.smtp_server, smtp_username=options.smtp_username, smtp_password=options.smtp_password, smtp_use_tls=options.smtp_use_tls, from_address=options.email_from) else: app = EvalException(error_application) serve(app, port=int(options.port)) WebError-0.10.3+dfsg/tests/test_error_middleware.py0000664000000000000000000000612211122572755021052 0ustar rootrootfrom webtest import TestApp, lint from weberror.errormiddleware import ErrorMiddleware from paste.util.quoting import strip_html def do_request(app, expect_status=500): app = lint.middleware(app) app = ErrorMiddleware(app, {}, debug=True) app = clear_middleware(app) testapp = TestApp(app) res = testapp.get('', status=expect_status, expect_errors=True) return res def clear_middleware(app): """ The fixture sets paste.throw_errors, which suppresses exactly what we want to test in this case. This wrapper also strips exc_info on the *first* call to start_response (but not the second, or subsequent calls. """ def clear_throw_errors(environ, start_response): headers_sent = [] def replacement(status, headers, exc_info=None): if headers_sent: return start_response(status, headers, exc_info) headers_sent.append(True) return start_response(status, headers) if 'paste.throw_errors' in environ: del environ['paste.throw_errors'] return app(environ, replacement) return clear_throw_errors ############################################################ ## Applications that raise exceptions ############################################################ def bad_app(): "No argument list!" return None def start_response_app(environ, start_response): "raise error before start_response" raise ValueError("hi") def after_start_response_app(environ, start_response): start_response("200 OK", [('Content-type', 'text/plain')]) raise ValueError('error2') def iter_app(environ, start_response): start_response("200 OK", [('Content-type', 'text/plain')]) return yielder(['this', ' is ', ' a', None]) def yielder(args): for arg in args: if arg is None: raise ValueError("None raises error") yield arg ############################################################ ## Tests ############################################################ def test_makes_exception(): res = do_request(bad_app) assert '' in formatter.make_wrappable('x'*1000) # I'm just going to test that this doesn't excede the stack limit: formatter.make_wrappable(';'*2000) assert (formatter.make_wrappable('this that the other') == 'this that the other') assert (formatter.make_wrappable('this that ' + ('x'*50) + ';' + ('y'*50) + ' and the other') == 'this that '+('x'*50) + ';' + ('y'*50) + ' and the other') WebError-0.10.3+dfsg/.hgignore0000664000000000000000000000020211466344257014552 0ustar rootroot # Automatically generated by `hgimportsvn` syntax:glob .svn .coverage *.pyc *.egg-info ez_setup *.egg-info *.egg test_logger.log WebError-0.10.3+dfsg/setup.cfg0000644000000000000000000000017111466345335014571 0ustar rootroot[egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 [nosetests] verbosity = 2 verbose = True with-doctest = True WebError-0.10.3+dfsg/WebError.egg-info/0000775000000000000000000000000011466345335016174 5ustar rootrootWebError-0.10.3+dfsg/WebError.egg-info/paster_plugins.txt0000755000000000000000000000001410722702726021763 0ustar rootrootPasteScript WebError-0.10.3+dfsg/WebError.egg-info/entry_points.txt0000755000000000000000000000034511466345333021473 0ustar rootroot [paste.filter_app_factory] main = weberror.evalexception:make_general_exception error_catcher = weberror.errormiddleware:make_error_middleware evalerror = weberror.evalexception:make_eval_exception WebError-0.10.3+dfsg/WebError.egg-info/SOURCES.txt0000755000000000000000000000231111466345333020054 0ustar rootroot.hgignore .hgtags CHANGELOG LICENSE MANIFEST.in README setup.cfg setup.py WebError.egg-info/PKG-INFO WebError.egg-info/SOURCES.txt WebError.egg-info/dependency_links.txt WebError.egg-info/entry_points.txt WebError.egg-info/not-zip-safe WebError.egg-info/paster_plugins.txt WebError.egg-info/requires.txt WebError.egg-info/top_level.txt tests/__init__.py tests/evaldemo.py tests/test_config.ini tests/test_error_middleware.py tests/test_formatter.py tests/test_reporter.py tests/reporter_output/.testdir weberror/__init__.py weberror/collector.py weberror/errormiddleware.py weberror/eval_template.html weberror/evalcontext.py weberror/evalexception.py weberror/formatter.py weberror/pdbcapture.py weberror/reporter.py weberror/eval-media/debug.js weberror/eval-media/jquery-1.2.1.min.js weberror/eval-media/jquery-1.2.3.pack.js weberror/eval-media/jquery.scrollTo-min.js weberror/eval-media/jquery.scrollTo.js weberror/eval-media/minus.jpg weberror/eval-media/plus.jpg weberror/eval-media/traceback.css weberror/exceptions/__init__.py weberror/exceptions/errormiddleware.py weberror/util/__init__.py weberror/util/errorapp.py weberror/util/escaping.py weberror/util/serial_number_generator.py weberror/util/source_encoding.pyWebError-0.10.3+dfsg/WebError.egg-info/not-zip-safe0000755000000000000000000000000110722702726020416 0ustar rootroot WebError-0.10.3+dfsg/WebError.egg-info/requires.txt0000755000000000000000000000004311466345333020570 0ustar rootrootWebOb Tempita Pygments Paste>=1.7.1WebError-0.10.3+dfsg/WebError.egg-info/PKG-INFO0000755000000000000000000000144511466345333017274 0ustar rootrootMetadata-Version: 1.0 Name: WebError Version: 0.10.3 Summary: Web Error handling and exception catching Home-page: UNKNOWN Author: Ben Bangert, Ian Bicking, Mark Ramm Author-email: UNKNOWN License: MIT Description: UNKNOWN Keywords: wsgi Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Programming Language :: Python Classifier: Topic :: Internet :: WWW/HTTP Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Topic :: Internet :: WWW/HTTP :: WSGI Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Application Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware WebError-0.10.3+dfsg/WebError.egg-info/dependency_links.txt0000755000000000000000000000000111466345333022241 0ustar rootroot WebError-0.10.3+dfsg/WebError.egg-info/top_level.txt0000755000000000000000000000001111466345333020715 0ustar rootrootweberror