如何在Django中进行调试,好方法?[关闭]

问题:如何在Django中进行调试,好方法?[关闭]

因此,我开始学习使用Python和更高版本的Django进行编码。第一次很难查看回溯,实际上要弄清楚我做错了什么以及语法错误在哪里。现在已经过去了一段时间,而且我想我已经有了调试Django代码的例程。由于这是我编码经验的早期,所以我坐下来,想知道自己的做法是否无效,并且可以更快地完成。我通常设法找到并纠正代码中的错误,但是我想知道是否应该更快地执行该操作?

我通常只使用Django启用时提供的调试信息。当事情按我预期的那样结束时,我因语法错误而使代码流中断很多,然后查看流中该点的变量以找出其中的代码在做什么,而不是我想要的。

但这可以改善吗?是否有一些好的工具或更好的方法来调试Django代码?

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?

I usually just use the debug info Django gives when enabled. When things do end up as I thought it would, I break the code flow a lot with a syntax error, and look at the variables at that point in the flow to figure out, where the code does something other than what I wanted.

But can this be improved? Are there some good tools or better ways to debug your Django code?


回答 0

有很多方法可以做到,但是最直接的方法就是简单地使用Python调试器。只需将以下行添加到Django视图函数中:

import pdb; pdb.set_trace()

要么

breakpoint()  #from Python3.7

如果尝试在浏览器中加载该页面,浏览器将挂起,并且提示您对实际执行的代码进行调试。

但是,还有其他选择(我不推荐使用):

* return HttpResponse({variable to inspect})

* print {variable to inspect}

* raise Exception({variable to inspect})

但是强烈建议所有类型的Python代码都使用Python调试器(pdb)。如果你已经到PDB,你想也想看看IPDB使用IPython中进行调试。

对pdb的一些更有用的扩展是

pdb ++,由 Antash建议。

pudb,由 PatDuJour建议。

Seafangs建议在Django中使用Python调试器

There are a bunch of ways to do it, but the most straightforward is to simply use the Python debugger. Just add following line in to a Django view function:

import pdb; pdb.set_trace()

or

breakpoint()  #from Python3.7

If you try to load that page in your browser, the browser will hang and you get a prompt to carry on debugging on actual executing code.

However there are other options (I am not recommending them):

* return HttpResponse({variable to inspect})

* print {variable to inspect}

* raise Exception({variable to inspect})

But the Python Debugger (pdb) is highly recommended for all types of Python code. If you are already into pdb, you’d also want to have a look at IPDB that uses ipython for debugging.

Some more useful extension to pdb are

pdb++, suggested by Antash.

pudb, suggested by PatDuJour.

Using the Python debugger in Django, suggested by Seafangs.


回答 1

我真的很喜欢Werkzeug的交互式调试器。它与Django的调试页面相似,不同之处在于您在回溯的每个级别上都获得了一个交互式shell。如果使用django-extensions,则会得到一个runserver_plus管理命令,该命令启动开发服务器,并为您提供Werkzeug的异常调试器。

当然,您只应在本地运行此命令,因为它使拥有浏览器的任何人都有权在服务器的上下文中执行任意python代码。

I really like Werkzeug‘s interactive debugger. It’s similar to Django’s debug page, except that you get an interactive shell on every level of the traceback. If you use the django-extensions, you get a runserver_plus managment command which starts the development server and gives you Werkzeug’s debugger on exceptions.

Of course, you should only run this locally, as it gives anyone with a browser the rights to execute arbitrary python code in the context of the server.


回答 2

模板标记的小工具:

@register.filter 
def pdb(element):
    import pdb; pdb.set_trace()
    return element

现在,您可以在模板内执行{{ template_var|pdb }}并输入一个pdb会话(假设您正在运行本地devel服务器),您可以在其中检查element您的心脏内容。

这是查看对象到达模板时发生了什么情况的一种很好的方法。

A little quickie for template tags:

@register.filter 
def pdb(element):
    import pdb; pdb.set_trace()
    return element

Now, inside a template you can do {{ template_var|pdb }} and enter a pdb session (given you’re running the local devel server) where you can inspect element to your heart’s content.

It’s a very nice way to see what’s happened to your object when it arrives at the template.


回答 3

有一些工具可以很好地协作,并且可以使您的调试任务更轻松。

最重要的是Django调试工具栏

然后,您需要使用Python 日志记录工具进行良好的日志记录。您可以将日志输出发送到日志文件,但是更简单的选择是将日志输出发送到firepython。要使用此功能,您需要使用带有firebug扩展名的Firefox浏览器。Firepython包含一个firebug插件,该插件将在Firebug标签中显示所有服务器端日志。

Firebug本身对于调试您开发的任何应用程序的Javascript方面也至关重要。(假设您当然有一些JS代码)。

我还喜欢使用django-viewtools通过pdb交互式地调试视图,但是我并没有那么多地使用它。

还有诸如推土机之类的更有用的工具来跟踪内存泄漏(SO的答案中也提供了其他一些很好的建议来进行内存跟踪)。

There are a few tools that cooperate well and can make your debugging task easier.

Most important is the Django debug toolbar.

Then you need good logging using the Python logging facility. You can send logging output to a log file, but an easier option is sending log output to firepython. To use this you need to use the Firefox browser with the firebug extension. Firepython includes a firebug plugin that will display any server-side logging in a Firebug tab.

Firebug itself is also critical for debugging the Javascript side of any app you develop. (Assuming you have some JS code of course).

I also liked django-viewtools for debugging views interactively using pdb, but I don’t use it that much.

There are more useful tools like dozer for tracking down memory leaks (there are also other good suggestions given in answers here on SO for memory tracking).


回答 4

我使用PyCharm(与Eclipse相同的pydev引擎)。确实可以帮助我直观地逐步查看我的代码并查看正在发生的事情。

I use PyCharm (same pydev engine as eclipse). Really helps me to visually be able to step through my code and see what is happening.


回答 5

到目前为止,几乎所有内容都已提及,因此,我仅补充一点,而不是pdb.set_trace()可以使用ipdb.set_trace()(它使用iPython),因此功能更强大(自动完成功能和其他功能)。这需要ipdb包,因此您只需要pip install ipdb

Almost everything has been mentioned so far, so I’ll only add that instead of pdb.set_trace() one can use ipdb.set_trace() which uses iPython and therefore is more powerful (autocomplete and other goodies). This requires ipdb package, so you only need to pip install ipdb


回答 6

我推django-pdbPyPI中。这是一个简单的应用程序,这意味着您不必每次想进入pdb都需要编辑源代码。

安装只是…

  1. pip install django-pdb
  2. 添加'django_pdb'到您的INSTALLED_APPS

您现在可以运行:manage.py runserver --pdb在每个视图的开始处进入pdb …

bash: manage.py runserver --pdb
Validating models...

0 errors found
Django version 1.3, using settings 'testproject.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

GET /
function "myview" in testapp/views.py:6
args: ()
kwargs: {}

> /Users/tom/github/django-pdb/testproject/testapp/views.py(7)myview()
-> a = 1
(Pdb)

并运行:manage.py test --pdb在测试失败/错误时进入pdb …

bash: manage.py test testapp --pdb
Creating test database for alias 'default'...
E
======================================================================
>>> test_error (testapp.tests.SimpleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File ".../django-pdb/testproject/testapp/tests.py", line 16, in test_error
    one_plus_one = four
NameError: global name 'four' is not defined
======================================================================

> /Users/tom/github/django-pdb/testproject/testapp/tests.py(16)test_error()
-> one_plus_one = four
(Pdb)

该项目托管在GitHub上,当然欢迎您贡献。

I’ve pushed django-pdb to PyPI. It’s a simple app that means you don’t need to edit your source code every time you want to break into pdb.

Installation is just…

  1. pip install django-pdb
  2. Add 'django_pdb' to your INSTALLED_APPS

You can now run: manage.py runserver --pdb to break into pdb at the start of every view…

bash: manage.py runserver --pdb
Validating models...

0 errors found
Django version 1.3, using settings 'testproject.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

GET /
function "myview" in testapp/views.py:6
args: ()
kwargs: {}

> /Users/tom/github/django-pdb/testproject/testapp/views.py(7)myview()
-> a = 1
(Pdb)

And run: manage.py test --pdb to break into pdb on test failures/errors…

bash: manage.py test testapp --pdb
Creating test database for alias 'default'...
E
======================================================================
>>> test_error (testapp.tests.SimpleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File ".../django-pdb/testproject/testapp/tests.py", line 16, in test_error
    one_plus_one = four
NameError: global name 'four' is not defined
======================================================================

> /Users/tom/github/django-pdb/testproject/testapp/tests.py(16)test_error()
-> one_plus_one = four
(Pdb)

The project’s hosted on GitHub, contributions are welcome of course.


回答 7

调试python的最简单方法是使用PTVS(适用于Visual Studio的Python工具),尤其是对于使用Visual Studio的程序员而言。步骤很简单:

  1. http://pytools.codeplex.com/下载并安装
  2. 设置断点并按F5。
  3. 您的断点被击中,您可以像调试C#/ C ++程序一样轻松地查看/更改变量。
  4. 就这样 :)

如果要使用PTVS调试Django,则需要执行以下操作:

  1. 在“项目设置”的“常规”选项卡中,将“启动文件”设置为“ manage.py”,这是Django程序的入口点。
  2. 在项目设置-调试选项卡中,将“脚本参数”设置为“ runserver –noreload”。关键是这里的“ –noreload”。如果您不设置它,您的断点将不会被击中。
  3. 好好享受。

The easiest way to debug python – especially for programmers that are used to Visual Studio – is using PTVS (Python Tools for Visual Studio). The steps are simple:

  1. Download and install it from http://pytools.codeplex.com/
  2. Set breakpoints and press F5.
  3. Your breakpoint is hit, you can view/change the variables as easy as debugging C#/C++ programs.
  4. That’s all :)

If you want to debug Django using PTVS, you need to do the following:

  1. In Project settings – General tab, set “Startup File” to “manage.py”, the entry point of the Django program.
  2. In Project settings – Debug tab, set “Script Arguments” to “runserver –noreload”. The key point is the “–noreload” here. If you don’t set it, your breakpoints won’t be hit.
  3. Enjoy it.

回答 8

我将pyDev与Eclipse 搭配使用非常好,设置断点,进入代码,查看任何对象和变量的值,然后尝试。

I use pyDev with Eclipse really good, set break points, step into code, view values on any objects and variables, try it.


回答 9

我使用PyCharm并一直坚持下去。它花了我一点钱,但我不得不说,我摆脱它的好处是无价的。我尝试从控制台进行调试,但我确实给予了很多荣誉,他们可以做到这一点,但是对我而言,能够直观地调试我的应用程序真是太好了。

我不得不说,PyCharm确实占用了大量内存。但是话又说回来,生活中没有什么是免费的。他们只是带有最新版本3。它在Django,Flask和Google AppEngine中也能很好地发挥作用。因此,总而言之,对于任何开发人员来说,这都是一个非常方便的工具。

如果您尚未使用它,建议您试用30天,以了解PyCharm的功能。我确定还有其他工具,例如Aptana。但是我想我也喜欢PyCharm的外观。我在那里调试我的应用程序感到非常自在。

I use PyCharm and stand by it all the way. It cost me a little but I have to say the advantage that I get out of it is priceless. I tried debugging from console and I do give people a lot of credit who can do that, but for me being able to visually debug my application(s) is great.

I have to say though, PyCharm does take a lot of memory. But then again, nothing good is free in life. They just came with their latest version 3. It also plays very well with Django, Flask and Google AppEngine. So, all in all, I’d say it’s a great handy tool to have for any developer.

If you are not using it yet, I’d recommend to get the trial version for 30 days to take a look at the power of PyCharm. I’m sure there are other tools also available, such as Aptana. But I guess I just also like the way PyCharm looks. I feel very comfortable debugging my apps there.


回答 10

有时候,当我想探索一种特定的方法并且召唤pdb太麻烦时,我会添加:

import IPython; IPython.embed()

IPython.embed() 启动一个IPython shell,该shell可以从调用它的地方访问局部变量。

Sometimes when I wan to explore around in a particular method and summoning pdb is just too cumbersome, I would add:

import IPython; IPython.embed()

IPython.embed() starts an IPython shell which have access to the local variables from the point where you call it.


回答 11

从我的角度来看,我们可以将常见的代码调试任务分解为三种不同的使用模式:

  1. 出现了一个异常runserver_plus’Werkzeug调试器进行了救援。在所有跟踪级别上运行自定义代码的能力是一个杀手er。而且,如果您完全陷入困境,则可以创建一个Gist,只需单击即可共享。
  2. 页面被渲染,但是结果是错误的:再次,Werkzeug摇摆不定。要在代码中创建断点,只需键入assert False要停止的位置。
  3. 代码工作不正确,但快速浏览无济于事。最有可能是算法问题。叹。然后,我通常火了调试器控制台PuDBimport pudb; pudb.set_trace()。与[i] pdb相比,主要优点是PuDB(看起来像80年代)使设置自定义监视表达式变得轻而易举。使用GUI调试一堆嵌套循环要简单得多。

啊,是的,模板的问题。最常见的问题(对我和我的同事而言)是错误的上下文:您没有变量,或者您的变量没有某些属性。如果您使用的是调试工具栏,则只需在“模板”部分检查上下文,或者,如果不够用的话,可以在填充完上下文后在视图代码中设置一个中断。

这样吧。

From my perspective, we could break down common code debugging tasks into three distinct usage patterns:

  1. 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.
  2. 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.
  3. 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.

Ah, yes, the templates’ woes. The most common (to me and my colleagues) problem is a wrong context: either you don’t have a variable, or your variable doesn’t have some attribute. If you’re using debug toolbar, just inspect the context at the “Templates” section, or, if it’s not sufficient, set a break in your views’ code just after your context is filled up.

So it goes.


回答 12

我强烈建议使用epdb(扩展的Python调试器)。

https://bitbucket.org/dugan/epdb

我喜欢epdb用于调试Django或其他Python网络服务器的一件事是epdb.serve()命令。这将设置一个跟踪并将其提供给您可以连接到的本地端口。典型用例:

我认为我要逐步进行。我将在要设置跟踪的位置插入以下内容。

import epdb; epdb.serve()

执行此代码后,我将打开一个Python解释器并连接到服务实例。我可以分析所有值,并使用标准的pdb命令(如n,s等)逐步执行代码。

In [2]: import epdb; epdb.connect()
(Epdb) request
<WSGIRequest
path:/foo,
GET:<QueryDict: {}>, 
POST:<QuestDict: {}>,
...
>
(Epdb) request.session.session_key
'i31kq7lljj3up5v7hbw9cff0rga2vlq5'
(Epdb) list
 85         raise some_error.CustomError()
 86 
 87     # Example login view
 88     def login(request, username, password):
 89         import epdb; epdb.serve()
 90  ->     return my_login_method(username, password)
 91
 92     # Example view to show session key
 93     def get_session_key(request):
 94         return request.session.session_key
 95

您可以随时了解有关键入epdb help的更多信息。

如果要同时服务或连接到多个epdb实例,则可以指定要监听的端口(默认为8080)。即

import epdb; epdb.serve(4242)

>> import epdb; epdb.connect(host='192.168.3.2', port=4242)

如果未指定,则主机默认为“ localhost”。我在这里进行了演示,以演示如何使用它来调试本地实例以外的其他东西,例如本地LAN上的开发服务器。显然,如果执行此操作,请注意设置的跟踪永远不会进入生产服务器!

快速说明一下,您仍然可以使用epdb(import epdb; epdb.set_trace())做与已接受答案相同的操作,但是由于我发现它非常有用,因此我想强调它的服务功能。

I highly recommend epdb (Extended Python Debugger).

https://bitbucket.org/dugan/epdb

One thing I love about epdb for debugging Django or other Python webservers is the epdb.serve() command. This sets a trace and serves this on a local port that you can connect to. Typical use case:

I have a view that I want to go through step-by-step. I’ll insert the following at the point I want to set the trace.

import epdb; epdb.serve()

Once this code gets executed, I open a Python interpreter and connect to the serving instance. I can analyze all the values and step through the code using the standard pdb commands like n, s, etc.

In [2]: import epdb; epdb.connect()
(Epdb) request
<WSGIRequest
path:/foo,
GET:<QueryDict: {}>, 
POST:<QuestDict: {}>,
...
>
(Epdb) request.session.session_key
'i31kq7lljj3up5v7hbw9cff0rga2vlq5'
(Epdb) list
 85         raise some_error.CustomError()
 86 
 87     # Example login view
 88     def login(request, username, password):
 89         import epdb; epdb.serve()
 90  ->     return my_login_method(username, password)
 91
 92     # Example view to show session key
 93     def get_session_key(request):
 94         return request.session.session_key
 95

And tons more that you can learn about typing epdb help at any time.

If you want to serve or connect to multiple epdb instances at the same time, you can specify the port to listen on (default is 8080). I.e.

import epdb; epdb.serve(4242)

>> import epdb; epdb.connect(host='192.168.3.2', port=4242)

host defaults to ‘localhost’ if not specified. I threw it in here to demonstrate how you can use this to debug something other than a local instance, like a development server on your local LAN. Obviously, if you do this be careful that the set trace never makes it onto your production server!

As a quick note, you can still do the same thing as the accepted answer with epdb (import epdb; epdb.set_trace()) but I wanted to highlight the serve functionality since I’ve found it so useful.


回答 13

我刚刚找到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中看到调用堆栈的漂亮图形输出,请结帐:https : //github.com/joerick/pyinstrument。只需将pyinstrument.middleware.ProfilerMiddleware添加到MIDDLEWARE_CLASSES,然后在请求URL的末尾添加?profile即可激活分析器。

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

I just found wdb (http://www.rkblog.rk.edu.pl/w/p/debugging-python-code-browser-wdb-debugger/?goback=%2Egde_25827_member_255996401). It has a pretty nice user interface / GUI with all the bells and whistles. Author says this about wdb –

“There are IDEs like PyCharm that have their own debuggers. They offer similar or equal set of features … However to use them you have to use those specific IDEs (and some of then are non-free or may not be available for all platforms). Pick the right tool for your needs.”

Thought i’d just pass it on.

Also a very helpful article about python debuggers: https://zapier.com/engineering/debugging-python-boss/

Finally, if you’d like to see a nice graphical printout of your call stack in Django, checkout: https://github.com/joerick/pyinstrument. Just add pyinstrument.middleware.ProfilerMiddleware to MIDDLEWARE_CLASSES, then add ?profile to the end of the request URL to activate the profiler.

Can also run pyinstrument from command line or by importing as a module.


回答 14

在Python代码的相应行中添加import pdb; pdb.set_trace()breakpoint() (形成python3.7)并执行它。执行将以交互式外壳程序停止。在外壳程序中,您可以执行Python代码(即打印变量)或使用以下命令:

  • c 继续执行
  • n 跳到同一功能的下一行
  • s 转到此函数或被调用函数的下一行
  • q 退出调试器/执行

另请参阅:https : //poweruser.blog/setting-a-breakpoint-in-python-438e23fe6b28

Add import pdb; pdb.set_trace() or breakpoint() (form python3.7) at the corresponding line in the Python code and execute it. The execution will stop with an interactive shell. In the shell you can execute Python code (i.e. print variables) or use commands such as:

  • c continue execution
  • n step to the next line within the same function
  • s step to the next line in this function or a called function
  • q quit the debugger/execution

Also see: https://poweruser.blog/setting-a-breakpoint-in-python-438e23fe6b28


回答 15

调试Django代码的最佳选择之一是通过wdb:https : //github.com/Kozea/wdb

wdb可与python 2(2.6、2.7),python 3(3.2、3.3、3.4、3.5)和pypy一起使用。甚至更好的是,可以用在python 3上运行的wdb服务器来调试python 2程序,反之亦然,或者用在第三台计算机的网页内的另一台计算机上运行的调试服务器来调试在计算机上运行的程序!更好的是,现在可以使用Web界面中的代码注入来暂停当前正在运行的python进程/线程。(这需要启用gdb和ptrace)换句话说,它是pdb的非常增强的版本,直接在浏览器中具有不错的功能。

安装并运行服务器,并在代码中添加:

import wdb
wdb.set_trace()

根据作者的说法,主要区别在于pdb

对于那些不了解项目的人,wdb是像pdb这样的python调试器,但是具有光滑的Web前端和许多其他功能,例如:

  • 源语法突出显示
  • 视觉断点
  • 使用jedi的交互式代码完成
  • 持久断点
  • 使用鼠标多线程/多处理支持进行深层对象检查
  • 远程调试
  • 观看表情
  • 在调试器代码版中
  • 流行的Web服务器集成可打破错误
  • 例如,在跟踪过程中发生异常中断(不是事后检验),与werkzeug调试器相反
  • 通过代码注入(在受支持的系统上)破坏当前正在运行的程序

它具有基于浏览器的出色用户界面。使用愉快!:)

One of your best option to debug Django code is via wdb: https://github.com/Kozea/wdb

wdb works with python 2 (2.6, 2.7), python 3 (3.2, 3.3, 3.4, 3.5) and pypy. Even better, it is possible to debug a python 2 program with a wdb server running on python 3 and vice-versa or debug a program running on a computer with a debugging server running on another computer inside a web page on a third computer! Even betterer, it is now possible to pause a currently running python process/thread using code injection from the web interface. (This requires gdb and ptrace enabled) In other words it’s a very enhanced version of pdb directly in your browser with nice features.

Install and run the server, and in your code add:

import wdb
wdb.set_trace()

According to the author, main differences with respect to pdb are:

For those who don’t know the project, wdb is a python debugger like pdb, but with a slick web front-end and a lot of additional features, such as:

  • Source syntax highlighting
  • Visual breakpoints
  • Interactive code completion using jedi
  • Persistent breakpoints
  • Deep objects inspection using mouse Multithreading / Multiprocessing support
  • Remote debugging
  • Watch expressions
  • In debugger code edition
  • Popular web servers integration to break on error
  • In exception breaking during trace (not post-mortem) in contrary to the werkzeug debugger for instance
  • Breaking in currently running programs through code injection (on supported systems)

It has a great browser-based user interface. A joy to use! :)


回答 16

我使用PyCharm和其他调试工具。也有一篇不错的文章集,关于为新手轻松设置这些东西。您可以从这里开始。它介绍了有关Django项目的PDB和GUI调试的一般信息。希望有人能从中受益。

I use PyCharm and different debug tools. Also have a nice articles set about easy set up those things for novices. You may start here. It tells about PDB and GUI debugging in general with Django projects. Hope someone would benefit from them.


回答 17

如果使用Aptana进行Django开发,请观看以下内容:http : //www.youtube.com/watch?v= qQh-UQFltJQ

如果没有,请考虑使用它。

If using Aptana for django development, watch this: http://www.youtube.com/watch?v=qQh-UQFltJQ

If not, consider using it.


回答 18

提到大多数选项。为了打印模板上下文,我为此创建了一个简单的库。参见https://github.com/edoburu/django-debugtools

您可以使用它来打印模板上下文,而无需任何{% load %}构造:

{% print var %}   prints variable
{% print %}       prints all

它使用定制的pprint格式在<pre>标签中显示变量。

Most options are alredy mentioned. To print template context, I’ve created a simple library for that. See https://github.com/edoburu/django-debugtools

You can use it to print template context without any {% load %} construct:

{% print var %}   prints variable
{% print %}       prints all

It uses a customized pprint format to display the variables in a <pre> tag.


回答 19

我发现Visual Studio Code非常适合调试Django应用。标准的python launch.json参数python manage.py与附加的调试器一起运行,因此您可以根据需要设置断点并逐步执行代码。

I find Visual Studio Code is awesome for debugging Django apps. The standard python launch.json parameters run python manage.py with the debugger attached, so you can set breakpoints and step through your code as you like.


回答 20

对于那些可能意外将pdb添加到实时提交中的人,我可以建议#Koobz答案的扩展名:

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

For those that can accidentally add pdb into live commits, I can suggest this extension of #Koobz answer:

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

回答 21

根据我自己的经验,有两种方法:

  1. 使用ipdb,它是像pdb一样的增强调试器。

    import ipdb;ipdb.set_trace()breakpoint() (来自python3.7)

  2. 使用django shell,只需使用下面的命令。在开发新视图时,这非常有帮助。

    python manage.py shell

From my own experience , there are two way:

  1. use ipdb,which is a enhanced debugger likes pdb.

    import ipdb;ipdb.set_trace() or breakpoint() (from python3.7)

  2. use django shell ,just use the command below. This is very helpfull when you are developing a new view.

    python manage.py shell


回答 22

我强烈建议使用PDB。

import pdb
pdb.set_trace()

您可以检查所有变量值,进入函数等等。 https://docs.python.org/2/library/pdb.html

用于检查对数据库的各种请求,响应和命中率。我正在使用django-debug-toolbar https://github.com/django-debug-toolbar/django-debug-toolbar

i highly suggest to use PDB.

import pdb
pdb.set_trace()

You can inspect all the variables values, step in to the function and much more. https://docs.python.org/2/library/pdb.html

for checking out the all kind of request,response and hits to database.i am using django-debug-toolbar https://github.com/django-debug-toolbar/django-debug-toolbar


回答 23

如此处其他文章所述-在代码中设置断点并遍历代码以查看其行为是否符合您的预期,这是学习Django之类的好方法,直到您对所有行为的方式有了很好的了解-以及代码的含义是在做。

为此,我建议使用WingIde。就像其他提到的IDE一样,它们易于使用,易于布局,易于设置断点,可以评估/修改堆栈等。非常适合可视化代码在逐步执行时的工作。我是它的忠实粉丝。

我也使用PyCharm-它具有出色的静态代码分析功能,有时可以帮助您在发现问题之前就发现问题。

如前所述,django-debug-toolbar是必不可少的-https: //github.com/django-debug-toolbar/django-debug-toolbar

尽管不是明确的调试或分析工具,但我最喜欢的工具之一是可从Django Snippets获得的SQL Printing Middleware网址https://djangosnippets.org/snippets/290/

这将显示您的视图已生成的SQL查询。这将使您对ORM的工作以及查询是否有效还是需要重新编写代码(或添加缓存)有一个很好的了解。

我发现它在开发和调试应用程序时密切关注查询性能非常有用。

另一个提示-我稍作修改,只为显示摘要而不显示SQL语句…。因此,在开发和测试时我总是使用它。我还补充说,如果len(connection.queries)大于预定义的阈值,它将显示一个额外的警告。

然后,如果发现不良情况(从性能或查询数量的角度来看),我将重新打开SQL语句的完整显示以查看发生了什么。当您与多个开发人员一起从事大型Django项目时,非常方便。

As mentioned in other posts here – setting breakpoints in your code and walking thru the code to see if it behaves as you expected is a great way to learn something like Django until you have a good sense of how it all behaves – and what your code is doing.

To do this I would recommend using WingIde. Just like other mentioned IDEs nice and easy to use, nice layout and also easy to set breakpoints evaluate / modify the stack etc. Perfect for visualizing what your code is doing as you step through it. I’m a big fan of it.

Also I use PyCharm – it has excellent static code analysis and can help sometimes spot problems before you realize they are there.

As mentioned already django-debug-toolbar is essential – https://github.com/django-debug-toolbar/django-debug-toolbar

And while not explicitly a debug or analysis tool – one of my favorites is SQL Printing Middleware available from Django Snippets at https://djangosnippets.org/snippets/290/

This will display the SQL queries that your view has generated. This will give you a good sense of what the ORM is doing and if your queries are efficient or you need to rework your code (or add caching).

I find it invaluable for keeping an eye on query performance while developing and debugging my application.

Just one other tip – I modified it slightly for my own use to only show the summary and not the SQL statement…. So I always use it while developing and testing. I also added that if the len(connection.queries) is greater than a pre-defined threshold it displays an extra warning.

Then if I spot something bad (from a performance or number of queries perspective) is happening I turn back on the full display of the SQL statements to see exactly what is going on. Very handy when you are working on a large Django project with multiple developers.


回答 24

使用pdbipdb。两者之间的区别在于ipdb支持自动完成。

对于pdb

import pdb
pdb.set_trace()

对于ipdb

import ipdb
ipdb.set_trace()

执行换行n击键,继续c击键。通过使用检查更多选项help(pdb)

use pdb or ipdb. Diffrence between these two is ipdb supports auto complete.

for pdb

import pdb
pdb.set_trace()

for ipdb

import ipdb
ipdb.set_trace()

For executing new line hit n key, for continue hit c key. check more options by using help(pdb)


回答 25

另一个建议。

您可以一起使用鼻子测试pdb,而不是pdb.set_trace()手动插入视图。这样做的好处是,您可以在首次启动时观察错误情况,可能会使用第三方代码。

今天对我来说是个错误。

TypeError at /db/hcm91dmo/catalog/records/

render_option() argument after * must be a sequence, not int

....


Error during template rendering

In template /opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/crispy_forms/templates/bootstrap3/field.html, error at line 28
render_option() argument after * must be a sequence, not int
18  
19          {% if field|is_checkboxselectmultiple %}
20              {% include 'bootstrap3/layout/checkboxselectmultiple.html' %}
21          {% endif %}
22  
23          {% if field|is_radioselect %}
24              {% include 'bootstrap3/layout/radioselect.html' %}
25          {% endif %}
26  
27          {% if not field|is_checkboxselectmultiple and not field|is_radioselect %}
28  

      {% if field|is_checkbox and form_show_labels %}

现在,我知道这意味着我烦恼了表单的构造函数,甚至我对哪个字段是个问题也有了很好的认识。但是,我可以使用pdb来查看模板中抱怨的脆性表单吗?

我可以。在鼻子测试中使用–pdb选项:

tests$ nosetests test_urls_catalog.py --pdb

一旦我遇到任何异常(包括正常处理的异常),pdb就会在发生异常的地方停止,我可以四处看看。

  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/forms.py", line 537, in __str__
    return self.as_widget()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/forms.py", line 593, in as_widget
    return force_text(widget.render(name, self.value(), attrs=attrs))
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/widgets.py", line 513, in render
    options = self.render_options(choices, [value])
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/widgets.py", line 543, in render_options
    output.append(self.render_option(selected_choices, *option))
TypeError: render_option() argument after * must be a sequence, not int
INFO lib.capture_middleware log write_to_index(http://localhost:8082/db/hcm91dmo/catalog/records.html)
INFO lib.capture_middleware log write_to_index:end
> /opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/widgets.py(543)render_options()
-> output.append(self.render_option(selected_choices, *option))
(Pdb) import pprint
(Pdb) pprint.PrettyPrinter(indent=4).pprint(self)
<django.forms.widgets.Select object at 0x115fe7d10>
(Pdb) pprint.PrettyPrinter(indent=4).pprint(vars(self))
{   'attrs': {   'class': 'select form-control'},
    'choices': [[('_', 'any type'), (7, (7, 'type 7', 'RECTYPE_TABLE'))]],
    'is_required': False}
(Pdb)         

现在,很明显,我对crispyfield构造函数的选择参数是因为它是列表中的列表,而不是元组的列表/元组。

 'choices': [[('_', 'any type'), (7, (7, 'type 7', 'RECTYPE_TABLE'))]]

整洁的是,此pdb发生在crispy的代码中,而不是我的,并且我不需要手动插入它。

An additional suggestion.

You can leverage nosetests and pdb together, rather injecting pdb.set_trace() in your views manually. The advantage is that you can observe error conditions when they first start, potentially in 3rd party code.

Here’s an error for me today.

TypeError at /db/hcm91dmo/catalog/records/

render_option() argument after * must be a sequence, not int

....


Error during template rendering

In template /opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/crispy_forms/templates/bootstrap3/field.html, error at line 28
render_option() argument after * must be a sequence, not int
18  
19          {% if field|is_checkboxselectmultiple %}
20              {% include 'bootstrap3/layout/checkboxselectmultiple.html' %}
21          {% endif %}
22  
23          {% if field|is_radioselect %}
24              {% include 'bootstrap3/layout/radioselect.html' %}
25          {% endif %}
26  
27          {% if not field|is_checkboxselectmultiple and not field|is_radioselect %}
28  

      {% if field|is_checkbox and form_show_labels %}

Now, I know this means that I goofed the constructor for the form, and I even have good idea of which field is a problem. But, can I use pdb to see what crispy forms is complaining about, within a template?

Yes, I can. Using the –pdb option on nosetests:

tests$ nosetests test_urls_catalog.py --pdb

As soon as I hit any exception (including ones handled gracefully), pdb stops where it happens and I can look around.

  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/forms.py", line 537, in __str__
    return self.as_widget()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/forms.py", line 593, in as_widget
    return force_text(widget.render(name, self.value(), attrs=attrs))
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/widgets.py", line 513, in render
    options = self.render_options(choices, [value])
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/widgets.py", line 543, in render_options
    output.append(self.render_option(selected_choices, *option))
TypeError: render_option() argument after * must be a sequence, not int
INFO lib.capture_middleware log write_to_index(http://localhost:8082/db/hcm91dmo/catalog/records.html)
INFO lib.capture_middleware log write_to_index:end
> /opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/widgets.py(543)render_options()
-> output.append(self.render_option(selected_choices, *option))
(Pdb) import pprint
(Pdb) pprint.PrettyPrinter(indent=4).pprint(self)
<django.forms.widgets.Select object at 0x115fe7d10>
(Pdb) pprint.PrettyPrinter(indent=4).pprint(vars(self))
{   'attrs': {   'class': 'select form-control'},
    'choices': [[('_', 'any type'), (7, (7, 'type 7', 'RECTYPE_TABLE'))]],
    'is_required': False}
(Pdb)         

Now, it’s clear that my choices argument to the crispy field constructor was as it was a list within a list, rather than a list/tuple of tuples.

 'choices': [[('_', 'any type'), (7, (7, 'type 7', 'RECTYPE_TABLE'))]]

The neat thing is that this pdb is taking place within crispy’s code, not mine and I didn’t need to insert it manually.


回答 26

在开发过程中,快速添加

assert False, value

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

During development, adding a quick

assert False, value

can help diagnose problems in views or anywhere else, without the need to use a debugger.