PyDev.Debugger icon indicating copy to clipboard operation
PyDev.Debugger copied to clipboard

500 error debugging on Django:

Open croepha opened this issue 8 years ago • 0 comments

I use PyCharm, and I have hacked together this bit of code:

# This will activate an attached PyCharm or PyDev debugger on a django 500
# error

# This makes it so that you dont have to set a breakpoint

# To use this, run the project in PyCharm or PyDev in debug mode, paste
#  or import this code somewhere ( i usually just paste it in urls.py )

# inspired by these:
#  https://github.com/jlubcke/pytest-pycharm/blob/master/pytest_pycharm.py
#  https://github.com/tomchristie/django-pdb/blob/master/django_pdb/management
#     /commands/runserver.py
def technical_500_response(request, exc_type, exc_value, tb, status_code=500):
    from django.views import debug

    try:
        import pydevd
        from pydevd import pydevd_tracing
    except ImportError:
        pass
    else:
        import threading

        frames = []
        while tb:
            frames.append(tb.tb_frame)
            tb = tb.tb_next

        thread = threading.current_thread()
        frames_by_id = dict([(id(frame), frame) for frame in frames])
        frame = frames[-1]
        debugger = pydevd.debugger
        if hasattr(debugger, "force_post_mortem_stop"):
            debugger.force_post_mortem_stop += 1

        pydevd_tracing.SetTrace(None)
        debugger.handle_post_mortem_stop(thread, frame, frames_by_id,
                                         (exc_type, exc_value, tb))

    return debug.original_technical_500_response(request, exc_type, exc_value,
                                                 tb, status_code=500)


from django.views import debug
if __debug__:
    if not getattr(debug, 'original_technical_500_response', None):
        print("Patching 500 Responder")
        debug.original_technical_500_response = debug.technical_500_response
        debug.technical_500_response = technical_500_response

I was wondering if I was missing something and there was an easier way to do this, or if maybe this could be included with PyDev some way?

croepha avatar Apr 04 '16 18:04 croepha