Debian Codegraph @

pecan/middleware/debug.py

raw
1 __CONFIG_HELP__ = b'''
2 <div class="traceback">
3 <b>To disable this interface, set </b>
4 <a target="window"
5 href="https://pecan.readthedocs.io/en/latest/deployment.html#disabling-debug-mode">
6 <pre>conf.app.debug = False</pre>
7 </a>
8 </div>
9 ''' # noqa
10
11 try:
12 import re
13 from backlash.debug import DebuggedApplication
14
15 class DebugMiddleware(DebuggedApplication):
16
17 body_re = re.compile(b'(<body[^>]*>)', re.I)
18
19 def debug_application(self, environ, start_response):
20 for part in super(DebugMiddleware, self).debug_application(
21 environ, start_response
22 ):
23 yield self.body_re.sub(b'<1>%s' % __CONFIG_HELP__, part)
24
25
26 except ImportError:
27 import logging
28 from traceback import print_exc
29 from pprint import pformat
30
31 from mako.template import Template
32 from io import StringIO
33 from webob import Response
34 from webob.exc import HTTPException
35
36 LOG = logging.getLogger(__file__)
37
38 debug_template_raw = '''<html>
39 <head>
40 <title>Pecan - Application Error</title>
41 <body>
42 <header>
43 <h1>
44 An error occurred!
45 </h1>
46 </header>
47 <div id="error-content">
48 <p>
49 %(config_help)s
50 Pecan offers support for interactive debugging by installing the <a href="https://pypi.python.org/pypi/backlash" target="window">backlash</a> package:
51 <br />
52 <b><pre>pip install backlash</pre></b>
53 ...and reloading this page.
54 </p>
55 <h2>Traceback</h2>
56 <div id="traceback">
57 <pre>${traceback}</pre>
58 </div>
59 <h2>WSGI Environment</h2>
60 <div id="environ">
61 <pre>${environment}</pre>
62 </div>
63 </div>
64 </body>
65 </html>
66 ''' % {'config_help': __CONFIG_HELP__} # noqa
67
68 debug_template = Template(debug_template_raw)
69
70 class DebugMiddleware(object):
71
72 def __init__(self, app, *args, **kwargs):
73 self.app = app
74
75 def __call__(self, environ, start_response):
76 try:
77 return self.app(environ, start_response)
78 except Exception as exc:
79 # get a formatted exception
80 out = StringIO()
81 print_exc(file=out)
82 LOG.exception(exc)
83
84 # get formatted WSGI environment
85 formatted_environ = pformat(environ)
86
87 # render our template
88 result = debug_template.render(
89 traceback=out.getvalue(),
90 environment=formatted_environ
91 )
92
93 # construct and return our response
94 response = Response()
95 if isinstance(exc, HTTPException):
96 response.status_int = exc.status
97 else:
98 response.status_int = 500
99 response.unicode_body = result
100 return response(environ, start_response)