Skip to content

Instantly share code, notes, and snippets.

@croepha
Last active July 28, 2022 13:02
Show Gist options
  • Save croepha/a1ac1c89c0abfbc74586 to your computer and use it in GitHub Desktop.
Save croepha/a1ac1c89c0abfbc74586 to your computer and use it in GitHub Desktop.
This will activate an attached PyCharm or PyDev debugger on a django 500 error
# 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):
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]
thread.additionalInfo.exception = (exc_type, exc_value, tb)
thread.additionalInfo.pydev_force_stop_at_exception = (frame, frames_by_id)
thread.additionalInfo.message = "500 error"
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.additionalInfo, thread)
return debug.original_technical_500_response(request, exc_type, exc_value, tb)
from django.views import debug
import logging
logger = logging.getLogger()
if not getattr(debug, 'original_technical_500_response', None):
logger.info("Patching 500 Responder")
debug.original_technical_500_response = debug.technical_500_response
debug.technical_500_response = technical_500_response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment