So, I started learning to code in Python and later Django. The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some time has passed now and some way along the way, I guess I got a routine in debugging my Django code. As this was done early in my coding experience, I sat down and wondered if how I was doing this was ineffective and could be done faster. I usually manage to find and correct the bugs in my code, but I wonder if I should be doing it faster?
我通常只使用Django启用时提供的调试信息。当事情确实像我想象的那样结束时,我用一个语法错误破坏了代码流,并查看流中那个点的变量,以找出代码在哪里做了与我想要的不同的事情。
但这种情况还能改善吗?是否有一些更好的工具或方法来调试Django代码?
有很多方法可以做到这一点,但最直接的是简单
使用Python调试器。只需在Django视图函数中添加如下一行:
import pdb; pdb.set_trace()
or
breakpoint() #from Python3.7
如果您试图在浏览器中加载该页,浏览器将挂起,并提示您对实际执行的代码进行调试。
但是也有其他的选择(我不推荐):
* return HttpResponse({variable to inspect})
* print {variable to inspect}
* raise Exception({variable to inspect})
但是对于所有类型的Python代码,强烈推荐使用Python调试器(pdb)。如果您已经开始使用pdb,那么您还需要了解使用ipython进行调试的IPDB。
对pdb有一些更有用的扩展
pdb++,由Antash建议。
pudb,由PatDuJour建议。
在Django中使用Python调试器,由Seafangs建议。
从我的角度来看,我们可以将常见的代码调试任务分解为三种不同的使用模式:
Something has raised an exception: runserver_plus' Werkzeug debugger to the rescue. The ability to run custom code at all the trace levels is a killer. And if you're completely stuck, you can create a Gist to share with just a click.
Page is rendered, but the result is wrong: again, Werkzeug rocks. To make a breakpoint in code, just type assert False in the place you want to stop at.
Code works wrong, but the quick look doesn't help. Most probably, an algorithmic problem. Sigh. Then I usually fire up a console debugger PuDB: import pudb; pudb.set_trace(). The main advantage over [i]pdb is that PuDB (while looking as you're in 80's) makes setting custom watch expressions a breeze. And debugging a bunch of nested loops is much simpler with a GUI.
啊,是的,模板的问题。最常见的问题(对我和我的同事来说)是错误的上下文:要么你没有变量,要么你的变量没有某些属性。如果你正在使用调试工具栏,只检查“模板”部分的上下文,或者,如果这还不够,在你的上下文填充后,在视图的代码中设置一个断点。
就这样。