from traceback import print_exc
from pprint import pformat
import pdb
from six.moves import cStringIO as StringIO
from mako.template import Template
from webob import Response
from .resources import (pecan_image, xregexp_js, syntax_js, syntax_css, theme,
brush)
debug_template_raw = '''
Pecan - Application Error
application error
To disable this interface, set
conf.app.debug = False
Traceback
${traceback}
% if not debugging:
Want to debug this request?
You can with a Python debugger breakpoint.
% endif
WSGI Environment
${environment}
'''
debug_template = Template(debug_template_raw)
__debug_environ__ = None
class PdbMiddleware(object):
def __init__(self, app, debugger):
self.app = app
self.debugger = debugger
def __call__(self, environ, start_response):
try:
return self.app(environ, start_response)
except:
self.debugger()
class DebugMiddleware(object):
"""A WSGI middleware that provides debugging assistance for development
environments.
To enable the debugging middleware, simply set the ``debug`` flag to
``True`` in your configuration file::
app = {
...
'debug': True,
...
}
Once enabled, the middleware will automatically catch exceptions raised by
your application, and display the Python stack trace and WSGI environment
in your browser for easy debugging.
To further aid in debugging, the middleware includes the ability to repeat
the offending request, automatically inserting a breakpoint, and dropping
your console into the Python debugger, ``pdb``.
For more information, refer to the `documentation for pdb
`_ available on the Python
website.
:param app: the application to wrap.
:param debugger: a callable to start debugging, defaulting to the Python
debugger, ``pdb``.
"""
def __init__(self, app, debugger=pdb.post_mortem):
self.app = app
self.debugger = debugger
def __call__(self, environ, start_response):
assert not environ['wsgi.multiprocess'], (
"The DebugMiddleware middleware is not usable in a "
"multi-process environment")
if environ.get('paste.testing'):
return self.app(environ, start_response)
# initiate a PDB session if requested
global __debug_environ__
debugging = environ['PATH_INFO'] == '/__pecan_initiate_pdb__'
if debugging:
PdbMiddleware(self.app, self.debugger)(
__debug_environ__, start_response
)
environ = __debug_environ__
try:
return self.app(environ, start_response)
except:
# save the environ for debugging
if not debugging:
__debug_environ__ = environ
# get a formatted exception
out = StringIO()
print_exc(file=out)
# get formatted WSGI environment
formatted_environ = pformat(environ)
# render our template
result = debug_template.render(
traceback=out.getvalue(),
environment=formatted_environ,
pecan_image=pecan_image,
xregexp_js=xregexp_js,
syntax_js=syntax_js,
brush=brush,
syntax_css=syntax_css,
theme=theme,
debugging=debugging
)
# construct and return our response
response = Response()
response.status_int = 400
response.unicode_body = result
return response(environ, start_response)