Debugging Applications

2018-02-24 15:39 更新

Debugging Applications

Depending on the WSGI gateway/server, exceptions are handled differently.But most of the time, exceptions go to stderr or the error log.

Since this is not the best debugging environment, Werkzeug provides aWSGI middleware that renders nice debugging tracebacks, optionally with anAJAX based debugger (which allows to execute code in the context of thetraceback's frames).

The interactive debugger however does not work in forking environmentswhich makes it nearly impossible to use on production servers. Also thedebugger allows the execution of arbitrary code which makes it a majorsecurity risk and must never be used on production machines because ofthat.

Enabling the Debugger

You can enable the debugger by wrapping the application in aDebuggedApplication middleware. Additionally there areparameters to the run_simple() function to enable it because thisis a common task during development.

class werkzeug.debug.DebuggedApplication(app, evalex=False, request_key='werkzeug.request', console_path='/console', console_init_func=None, show_hidden_frames=False, lodgeit_url=None)
Enables debugging support for a given application:

from werkzeug.debug import DebuggedApplication
from myapp import app
app = DebuggedApplication(app, evalex=True)

The evalex keyword argument allows evaluating expressions in atraceback's frame context.

0.9 新版功能: The lodgeit_url parameter was deprecated.

  • app – the WSGI application to run debugged.
  • evalex – enable exception evaluation feature (interactivedebugging). This requires a non-forking server.
  • request_key – The key that points to the request object in thsenvironment. This parameter is ignored in currentversions.
  • console_path – the URL for a general purpose console.
  • console_init_func – the function that is executed before startingthe general purpose console. The return valueis used as initial namespace.
  • show_hidden_frames – by default hidden traceback frames are skipped.You can show them by setting this parameterto True.

Using the Debugger

Once enabled and an error happens during a request you will see a detailedtraceback instead of a general “internal server error”. If you have theevalex feature enabled you can also get a traceback for every frame inthe traceback by clicking on the console icon.

Once clicked a console opens where you can execute Python code in: