如何在 Django 中调试,好方法? [英] How to debug in Django, the good way?

查看:40
本文介绍了如何在 Django 中调试,好方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我开始学习用 Python 和后来的 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?

我通常只使用 Django 在启用时提供的调试信息.当事情最终如我所想的那样结束时,我会用语法错误破坏代码流程,然后查看流程中该点的变量以找出代码在何处执行了我想要的操作之外的其他操作.

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.

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

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

推荐答案

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

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()

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})

但是强烈建议将 Python 调试器 (pdb) 用于所有类型的 Python 代码.如果你已经进入 pdb,你还想看看 IPDB 使用 ipython 进行调试.

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.

一些更有用的 pdb 扩展是

Some more useful extension to pdb are

pdb++,由 Antash.

pudb,由 PatDuJour.

在 Django 中使用 Python 调试器,由 Seafangs 推荐.

这篇关于如何在 Django 中调试,好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆