How to debug Django using the Python Debugger PDB

Even if that seems common sense, i found out that there’s not that much sources that explains how to use PDB with Django’s bundle webserver.  So here we go, let’s say you have some treatment like that :

def search(request):
	"""
	  	search (it's written up there).
	"""
	if request.method == 'POST':
		item = request.POST['item']
		# separate numeric part from string part and
		# add a % in case no numeric value is provided
	   	(num, test) = re.match("([d]*)([D]*)", item).groups()
		if not num:
			num = "%"
                .... # query in database

Now what we want to check, is that the « not num » part is doing its job in replacing any non-numeric part by a wildcard. so we’ll add this statement « import pdb; pdb.set_trace() » to set up a breakpoint that PDB will be able to use :

def search(request):
	"""
	  	ase.
	"""
	if request.method == 'POST':
		item = request.POST['item']
		# separate numeric part from string part and
		# add a % in case no numeric value is provided
	   	(num, test) = re.match("([d]*)([D]*)", item).groups()
                # the breakpoint will be here :
                import pdb; pdb.set_trace()
		if not num:
			num = "%"
                .... # query in database

And then, all we need to do is run the standalone embedded web server of Django using pdb. At first PDB (just like GDB) will wait for you to use the command c (continue) to launch the program and will only stop when he reaches a breakpoint :

 python -m pdb manage.py runserver

Eventually when you’ll reach the breakpoint, you can use the commands locals(), globals() to see all the variables you can access. For more on how to use PDB and debugging in Django i refer you to the nice tutorial by Mike Tigas.

Vale

Publicités

Laisser un commentaire

Entrez vos coordonnées ci-dessous ou cliquez sur une icône pour vous connecter:

Logo WordPress.com

Vous commentez à l'aide de votre compte WordPress.com. Déconnexion / Changer )

Image Twitter

Vous commentez à l'aide de votre compte Twitter. Déconnexion / Changer )

Photo Facebook

Vous commentez à l'aide de votre compte Facebook. Déconnexion / Changer )

Photo Google+

Vous commentez à l'aide de votre compte Google+. Déconnexion / Changer )

Connexion à %s

%d blogueurs aiment cette page :