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代码?


当前回答

我使用pyDev与Eclipse真的很好,设置断点,进入代码,查看任何对象和变量的值,尝试它。

其他回答

在开发过程中,快速添加

assert False, value

可以帮助诊断视图或其他任何地方的问题,而不需要使用调试器。

我发现Visual Studio Code用于调试Django应用程序非常棒。标准的python启动。Json参数运行python manage.py,并附带调试器,因此你可以设置断点,并按自己的喜好逐步执行代码。

对于那些不小心将pdb添加到实时提交的人,我可以建议这个扩展#Koobz的答案:

@register.filter 
def pdb(element):
    from django.conf import settings
    if settings.DEBUG:    
        import pdb
        pdb.set_trace()
    return element

我刚找到wdb (http://www.rkblog.rk.edu.pl/w/p/debugging-python-code-browser-wdb-debugger/?goback=%2Egde_25827_member_255996401)。它有一个非常漂亮的用户界面/ GUI,所有的铃铛和口哨。作者这样说wdb -

“像PyCharm这样的ide有自己的调试器。它们提供了相似或相同的功能……然而,要使用它们,你必须使用那些特定的ide(其中一些是非免费的,或者可能不适用于所有平台)。根据你的需要选择合适的工具。”

我想我应该把它传下去。

这也是一篇关于python调试器的非常有用的文章: https://zapier.com/engineering/debugging-python-boss/

最后,如果你想在Django中看到一个漂亮的调用堆栈的图形打印输出,checkout: https://github.com/joerick/pyinstrument。只需将pyinstrument.middleware.ProfilerMiddleware添加到MIDDLEWARE_CLASSES中,然后将?profile添加到请求URL的末尾以激活剖析器。

也可以从命令行或导入作为模块运行pyinstrument。

我非常喜欢Werkzeug的交互式调试器。它类似于Django的调试页面,除了在回溯的每一层都有一个交互式shell。如果你使用django-extensions,你会得到一个runserver_plus管理命令,它会启动开发服务器,并在异常时为你提供Werkzeug的调试器。

当然,您应该只在本地运行它,因为它赋予任何使用浏览器的人在服务器上下文中执行任意python代码的权利。