如何在打开autoreload的情况下在VSCode中调试Django

2024-05-23 22:45:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我在VSCode(Django应用程序)中设置了调试,它在默认设置下运行良好。但是,在调试时,似乎无法自动重新加载。这在VSCodedocs中说明:

Note that automatic reloading of Django apps is not possible while debugging.

我想知道是否有某种方法可以使调试(断点等)在Django中启用重新加载的情况下工作


Tags: appsofdjango应用程序thatisnotvscode
1条回答
网友
1楼 · 发布于 2024-05-23 22:45:57

事实证明,您可以使用Microsoft的debugpy工具来实现这一点

Django在启用重新加载时启动两个进程(默认设置),其中一个是父进程,另一个是执行重新加载魔法的子进程

Django通过在子流程中将环境变量RUN_MAIN设置为true来区分这两个流程(重新加载)。请参阅:https://github.com/django/django/blob/8a902b7ee622ada258d15fb122092c1f02b82698/django/utils/autoreload.py#L241

通过稍微调整manage.py,我们可以在父进程中启动一个调试侦听器,并使其在任何重新加载后都能存活

  1. 添加debugpy到您管理需求的方式(requirements.txt等)

  2. 添加以下函数以初始化调试器:

def initialize_debugger():
    import debugpy
    
    # optionally check to see what env you're running in, you probably only want this for 
    # local development, for example: if os.getenv("MY_ENV") == "dev":

    # RUN_MAIN envvar is set by the reloader to indicate that this is the 
    # actual thread running Django. This code is in the parent process and
    # initializes the debugger
    if not os.getenv("RUN_MAIN"):
        debugpy.listen(("0.0.0.0", 9999))
        sys.stdout.write("Start the VS Code debugger now, waiting...\n")
        debugpy.wait_for_client()
        sys.stdout.write("Debugger attached, starting server...\n")

  1. 将manage.py中的main函数更改如下:
    def main()
        # <...>
        initialize_debugger()  # add this
        execute_from_command_line(sys.argv)

  1. 修改VSCode中的launch.json配置以连接到端口9999(从上面):
        {
            "name": "Python: Remote Attach (DebugPy)",
            "type": "python",
            "request": "attach",
            "port": 9999,
            "host": "localhost",
        },

提示:您可以禁用“未捕获异常”,因为重新加载本身会导致系统退出

相关问题 更多 >