WebError Traceback:
| >> | 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 |
%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('
' 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 (''
'%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 '
%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 = ['
| %s | |
|---|---|
| %s | ' % (odd and 'odd' or 'even', self.quote(name))) table.append( '%s |
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\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
`` 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.py 0000664 0000000 0000000 00000072613 11164461161 020022 0 ustar root root """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 = ''
}}
{{name}}
{{preserve_whitespace(value_html, quote=False)|html}}{{if expand_html}}
...
{{endif}}
{{endfor}}
''', 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 '''
''' % (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/ 0000775 0000000 0000000 00000000000 11466345335 015557 5 ustar root root WebError-0.10.3+dfsg/weberror/util/escaping.py 0000664 0000000 0000000 00000017123 11016722455 017717 0 ustar root root # 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;' % 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.py 0000664 0000000 0000000 00000007620 11070224122 023010 0 ustar root root # (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.py 0000664 0000000 0000000 00000003156 11010417022 021256 0 ustar root root """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.py 0000644 0000000 0000000 00000000462 10727022360 017750 0 ustar root root """
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__.py 0000644 0000000 0000000 00000000000 10723213331 017635 0 ustar root root WebError-0.10.3+dfsg/weberror/__init__.py 0000644 0000000 0000000 00000000002 10723213331 016662 0 ustar root root #
WebError-0.10.3+dfsg/weberror/collector.py 0000664 0000000 0000000 00000047443 11466344242 017152 0 ustar root root # (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.py 0000664 0000000 0000000 00000011616 11466344257 017314 0 ustar root root from 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/ 0000775 0000000 0000000 00000000000 11466345335 016763 5 ustar root root WebError-0.10.3+dfsg/weberror/exceptions/errormiddleware.py 0000664 0000000 0000000 00000001243 11003173153 022504 0 ustar root root import 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__.py 0000644 0000000 0000000 00000000002 10770066101 021046 0 ustar root root #
WebError-0.10.3+dfsg/weberror/reporter.py 0000664 0000000 0000000 00000011531 11335430006 017000 0 ustar root root # (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/README 0000644 0000000 0000000 00000000000 10723213331 013600 0 ustar root root WebError-0.10.3+dfsg/LICENSE 0000644 0000000 0000000 00000004277 11012136673 013756 0 ustar root root EXCEPT 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.in 0000664 0000000 0000000 00000000126 11003174504 014471 0 ustar root root recursive-include weberror/eval-media *
recursive-include weberror eval_template.html
WebError-0.10.3+dfsg/.hgtags 0000664 0000000 0000000 00000000735 11335430037 014223 0 ustar root root 641409089c70fa587f9535f2752eb0424dbf9d65 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/CHANGELOG 0000664 0000000 0000000 00000002355 11466345271 014171 0 ustar root root WebError 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-INFO 0000664 0000000 0000000 00000001445 11466345335 014054 0 ustar root root Metadata-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.py 0000664 0000000 0000000 00000003254 11466345133 014465 0 ustar root root from 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/ 0000775 0000000 0000000 00000000000 11466345335 014115 5 ustar root root WebError-0.10.3+dfsg/tests/reporter_output/ 0000775 0000000 0000000 00000000000 11466345335 017377 5 ustar root root WebError-0.10.3+dfsg/tests/reporter_output/.testdir 0000644 0000000 0000000 00000000000 10723213331 021023 0 ustar root root WebError-0.10.3+dfsg/tests/test_config.ini 0000644 0000000 0000000 00000000314 10727022360 017103 0 ustar root root [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__.py 0000644 0000000 0000000 00000000002 10723213331 016175 0 ustar root root #
WebError-0.10.3+dfsg/tests/evaldemo.py 0000664 0000000 0000000 00000004730 11032256447 016261 0 ustar root root from 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.py 0000664 0000000 0000000 00000006122 11122572755 021052 0 ustar root root from 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 ' 