Skip to content

Instantly share code, notes, and snippets.

@kxxoling
Created November 28, 2015 06:26
Show Gist options
  • Save kxxoling/00f5bb306b5a3398fa0d to your computer and use it in GitHub Desktop.
Save kxxoling/00f5bb306b5a3398fa0d to your computer and use it in GitHub Desktop.
在 Tornado 3 中使用 wekzeug 的调试工具。
from werkzeug.debug.tbtools import get_current_traceback as get_traceback_context
from werkzeug.debug import DebuggedApplication
import tornado.ioloop
import tornado.web
import tornado.wsgi
class Handler(tornado.web.RequestHandler):
def get_error_html(self, status_code, **kwargs):
assert isinstance(self.application, DebugApplication)
traceback = self.application.get_current_traceback()
keywords = self.application.get_traceback_renderer_keywords()
html = traceback.render_full(**keywords).encode('utf-8', 'replace')
return html.replace(b'WSGI', b'tornado')
class BrokenHandler(Handler):
def get(self):
raise Exception('A Test Exception')
self.write("You'll never get this!")
class DebugApplication(tornado.web.Application):
def __init__(self, *args, **kwargs):
self.debug_app = DebuggedApplication(self.debug_wsgi_app, evalex=True)
self.debug_container = tornado.wsgi.WSGIContainer(self.debug_app)
super(DebugApplication, self).__init__(*args, **kwargs)
def __call__(self, request):
if '__debugger__' in request.uri:
return self.debug_container(request)
return super(DebugApplication, self).__call__(request)
@classmethod
def debug_wsgi_app(cls, environ, start_response):
status = '500 Internal Server Error'
response_headers = [('Content-type', 'text/plain')]
start_response(status, response_headers)
return ['Failed to load debugger.\n']
def get_current_traceback(self):
traceback = get_traceback_context(skip=2, show_hidden_frames=False, ignore_system_exceptions=True)
for frame in traceback.frames:
self.debug_app.frames[frame.id] = frame
self.debug_app.tracebacks[traceback.id] = traceback
return traceback
def get_traceback_renderer_keywords(self):
return dict(evalex=self.debug_app.evalex, secret=self.debug_app.secret)
if __name__ == '__main__':
handlers = [('/', BrokenHandler), ]
app = DebugApplication(handlers, debug=True)
app.listen(8888)
tornado.ioloop.IOLoop.instance().start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment