středa 14. října 2009

Simple debugging of Ajax in Django

One of the great features of Django is that when in debugging mode something goes wrong with your code, you will see the traceback of the error and many other useful information directly in your browsers window.


This is cool and helps you to quickly debug your code. The problem comes when you start to put Ajax into your site. Then the result of a request is not directly displayed in the window and all you can see is the HTTP return code of 500 in the log of your server.


In this short post I will show a simple yet useful solution to this problem. The goal is to get the error messages somehow. In my case, it is sufficient to read it from the log of the development server. To accomplish this, I wrote a simple decorator (wrapper) that you can use in your view function (or anywhere else if you wish). Like this:



@console_debug
def my_awesome_view(req,....

The code for the decorator, which I choose to place in a separate module, but you can also place it somewhere in views.py, is as follows:



import sys
import traceback

def console_debug(f):
def x(*args, **kw):
try:
ret = f(*args, **kw)
except Exception, e:
print >> sys.stderr, "ERROR:", str(e)
exc_type, exc_value, tb = sys.exc_info()
message = "Type: %s\nValue: %s\nTraceback:\n\n%s" % (exc_type, exc_value, "\n".join(traceback.format_tb(tb)))
print >> sys.stderr, message
raise
else:
return ret
return x

4 komentáře:

  1. Have you tried using Firebug for Firefox? It allows you to see the requests and return codes.

    OdpovědětVymazat
  2. Hi Noel,
    I use Firebug from time to time, but it never occurred to me that it would be useful in this case. Thanks for the good tip, it will certainly become part of my everyday toolbox.

    OdpovědětVymazat
  3. Tento komentář byl odstraněn administrátorem blogu.

    OdpovědětVymazat
  4. I was searching for a solution of this problem. This just helped me speeding up in trouble-shooting one of the on-demand processes I'm working on. Thanks for the post.
    Web Developer New York

    OdpovědětVymazat