python - 如何在 Django 的运行服务器中进行事后调试?

我目前正在调试一个导致异常的 Django 项目。我想进入 ipdb 事后调试器。我试过将 ipdb 作为脚本调用(参见 https://docs.python.org/3/library/pdb.html ),但这只是让我进入了第一行代码:

> python -m ipdb manage.py runserver
> /Users/kurtpeek/myproject/manage.py(2)<module>()
      1 #!/usr/bin/env python
----> 2 import os
      3 import sys

ipdb> 

如果我按 c继续,我只会遇到错误,不可能进入调试器事后分析。大概我可以按 n (next) 直到出现错误,但这会很麻烦。

有没有办法通过事后调试运行 python manage.py runserver

最佳答案

如果您知道导致异常的行,但不知道导致异常的内部有多“深”,您可以通过捕获异常并调用 ipdb 来获得事后调试器.post_mortem() 在异常处理程序中。

例如,将您的代码更改为:

def index(request):
    output = function_that_causes_some_exception()
    return HttpResponse(output)

对此:

def index(request):
    try:
        output = function_that_causes_some_exception()
    except:
        import ipdb
        ipdb.post_mortem()
        # Let the framework handle the exception as usual:
        raise
    return HttpResponse(output)

顺便说一句,对于可能从其他线程在控制台中喷出内容的服务器框架,我强烈推荐 wdb ,这样您就可以在浏览器中舒适地调试您的 Django 应用程序:

def index(request):
    try:
        output = function_that_causes_some_exception()
    except:
        import wdb
        wdb.post_mortem()
        # Let the framework handle the exception as usual:
        raise
    return HttpResponse(output)

https://stackoverflow.com/questions/57227938/

相关文章:

javascript - 在 Angular 6 中处理来自第三方 URL 的发布响应。无法发布错误

node.js - 当调用 Axios GET 并且 express 服务器发送 .json() 时

javascript - 无法让用 chrome 录制的音频 blob 在 safari 中工作

javascript - 我可以使用 jQuery globaleval 而不是 eval 来逃避内

caching - Shopify 缓存 - 哪些操作导致清除缓存

macos - 错误 : command 'gcc' failed with exit status

python - 导入 pycurl : Library not loaded: @rpath/li

php - LinkedIn Share API 'ugcPosts' 响应 504 PHP 网关超

css - 自托管字体在 Gatsby 和 Safari 中不起作用

google-cloud-functions - Firebase 日志错误 FAILED_PREC