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

查看:22
本文介绍了如何在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天全站免登陆