Skip to content
Back to Blog

Django Debug with a Threaded Pdb

Rich Jones

Jan 4, 2017 10:45:00 AM

Quick tip time!

Need to debug a Django website or API that you're building, but don't want to disrupt service for other developers or clients using your app? Well then, you're in luck, because this tip is for you!

If you don't know already, the python debugger, aka pdb, is the best tool ever. Just call pdb.set_trace() in your python apps and get an interactive shell wherever you want. Awesome!

However, that doesn't work well for debugging APIs, because it will cause your web server to either time out or return 400 or 500 errors because the debugger blocks the app from returning a real HTTP response.

However, with this little snippet, you can have your cake an eat it to! It will create a new thread with your debugger, and return an HTTP response to your client. Yay!

  from django.http import HttpResponse, HttpResponseRedirect
  from django.template import RequestContext
  from django.shortcuts import get_object_or_404, render_to_response
  import threading
  import pdb
   
  def threaded_pdb_example_page(request):
   
  def debug(args, **kwargs):
  request = args['request']
  import pdb
  pdb.set_trace()
   
  t = threading.Thread(target=debug,
  args=[request],
  kwargs={'fail_silently': True})
   
  t.setDaemon(True)
  t.start()
   
  return render_to_response('my_app/my_template.html',
  {'success': True},
  context_instance=RequestContext(request))
view raw threaded_pdb.py hosted with ❤ by GitHub

 

There you go! See ways to improve this script? Feel free to fork and comment below!

Written By:

Rich Jones

Want to get our totally not sh*tty weekly newsletter?

Sometimes The Wayfarer is funny, sometimes insightful, but always the least spammy newsletter this side of Tatooine.