怎么调试django程序呢? models还好,可以在django shell中很方便的调试 而view中只能发送httpresponse对象到浏览器,print打印的东西不会在浏览器输出

找到了这篇文章 http://simonwillison.net/2008/May/22/debugging/

收获:

  1. 如果用的是development server,print输出到了对应的terminal中

  2. 可以使用python的logging module

在setting中:

import logging
logging.basicConfig(
    level = logging.DEBUG,
    format = '%(asctime)s %(levelname)s %(message)s',
)

view中

def my_view(request):
    import logging
    logging.debug("A log message")
    ...

还是输出到终端了

如果想写到文件中:

logging.basicConfig(
    level = logging.DEBUG,
    format = '%(asctime)s %(levelname)s %(message)s',
    filename = '/tmp/myapp.log',
    filemode = 'w'
)

然后 tail -f /tmp/myapp.log, 这个产品环境中也可以使用

  1. 使用pdb

在view中

import pdb; pdb.set_trace()

浏览器阻塞,development server对应的终端出现了pdb的窗口

常用命令

list
    Shows the lines of source code around your current point of execution. You can run it multiple times to increase the amount of source code displayed.
n
    Execute the next line
s
    Same as n, but steps in to any functions that are called. You can quickly get lost in a twisty maze of code with this command, but that’s OK because...
r
    Continues execution until the current function returns
u
    Goes UP one level in the stack—so you can see the function that called the function you are currently in
d
    Goes DOWN again
locals()
    not a pdb command, but handy for seeing what’s in your current scope 

4:更有用的是 Django’s TestClient

>>> from django.test.client import Client
>>> c = Client()
>>> response = c.get("/") # The homepage
>>> response
<django.http.HttpResponse object at 0x2300470>
>>> print response
Vary: Cookie
Content-Type: text/html; charset=utf-8

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "<http://www.w3.org/TR/html4/strict.dtd>">
<html>
...