Debugging Python web applications

Usually, Python web applications aren’t distributed in some sort of “compiled” release format - but they can be. We’ll discuss reverse engineering compiled Python applications if we need to, but for now we’ll just talk about about plaintext web applications.

The best way to debug Python web applications is to use an IDE like VSCode or PyCharm. With VSCode, we can remotely debug target applications using the ptvsd Python package. Insert the following magic words before a Python web application starts to enable remote debugging:

import ptvsd
ptvsd.enable_attach(redirect_output=True)
print("Now ready for the IDE to connect to the debugger")
ptvsd.wait_for_attach()

By default, ptvsd listens on port 5678 for a connection from the VSCode remote debugger. To initiate remote debugging, connecting to our target web application with VSCode, we can use the following launch.json specification:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python Debugger: Remote Attach",
            "type": "debugpy",
            "request": "attach",
            "connect": {
                "host": "{DEBUG_TARGET_IP_ADDRESS}",
                "port": 5678
            },
            "pathMappings": [
                {
                    "localRoot": "${workspaceFolder}",
                    "remoteRoot": "{PATH_TO_SOURCE_CODE}"
                }
            ]
        }
    ]
}

DEBUG_TARGET_IP_ADDRESS is the IP address of the host running the Python web application. PATH_TO_SOURCE_CODE is the path to the Python web application source code we’re debugging in VSCode.

That’s it! It should “just work” - if not you can always read the documentation to debug.