Debugging Flask App with VS Code Made Easy

In this tutorial you will learn how about Debugging Flask App with VS Code. This article has a detailed walk through on how to setup Visual Studio Code IDE for debugging Flask application and demonstrates step by step debugging of the application.

Debugging Flask App with VS Code Made Easy - TutLinks
Debugging Flask App with VS Code Made Easy – TutLinks

Table of Contents

Key take away

By the end of this tutorial you will

  • Understand the definition of Debugging
  • Purpose of Debugging
  • Most widely used ways to Debug a Software Application
  • IDEs with Debug Capabilities for Python
  • Setting up VS Code IDE to debug Flask Application written in Python
  • Add breakpoints, run and debug the Flask Application
  • Various function keys to debug the Flask Application
  • A brief about debug Variables, adding Watch to variable or method of choice, understand call stack and breakpoints

Simple definition of Debugging

As a software engineer, it is of utmost interest to know what is happening behind the scenes of a running application. This can be done with the help of a process called Debugging. Debugging is the process of understanding the workflow of any software application, analyse the behavior and visualize the state of the software application and troubleshoot problems if any that occur in the software application.

Intention of Debugging Software Applications

Software Developers debug any software application for two specific reasons. One is to understand the Software Application and the other major reason is to troubleshoot and fix prevalent issues in the application. The second reason of Debugging is highly obvious in the Software Industry to troubleshoot and fix any scenarios that didn’t get covered under any unit or integration tests or the bugs that arise due to uncaught exceptions.

Ways to Debug Software Application

There are several ways to debug any software application. Most widely used way is to observe trace log files in case you don’t have development environment and act towards resolving any problem or understand whats happening in the application routine. The other recommended way is to actually debug through the application workflow using the IDEs that provide infrastructure to debug programming through each and every line of code. Obviously it is required to have access to the full source code and plugins or extensions or an IDE that is capable of debugging specific programming language under test.

IDEs with Debugging Capabilities for Python

Thanks to many popular IDEs that support debugging capabilities for Python like Visual Studio, Visual Studio Code, PyCharm to name a few. Visual Studio Code with its popular extension for Python ms-python.python provides excellent debug capabilities that enables to debug multi-threaded, remote Python applications with a proper setup in launch.json file.

In this tutorial we will see how to setup VS Code IDE to debug a Flask application written in Python. Please be noted that the debugging different frameworks of Python such as Flask, Django etc,. require different settings. And those debug settings will be stored in launch.json

Setup VS Code IDE to debug Flask Application

Before you proceed it is recommended to have a read through of the tutorial that helps you Setup VS Code IDE for Flask Development. Alternatively, to speed things up, you can go through the video tutorial to Get started with Python on VS Code in just 6 minutes.

Open and Setup the Flask app in VS Code

Follow the sequence of steps below to setup the Hello World Flask application in VS Code.

Execute the following shell script based on the OS you are working on. You need to copy and paste the below script in your command terminal.

Windows OS

git clone https://github.com/windson/flask-tutorials.git
cd flask-tutorials
git checkout hello-world-flask
python -m venv env
env\Scripts\activate
python -m pip install --upgrade pip
pip install -r requirements.txt
code .

Unix OS Variants

git clone https://github.com/windson/flask-tutorials.git
cd flask-tutorials
git checkout hello-world-flask
python3 -m venv env
source ./env/bin/activate
python -m pip install --upgrade pip
pip install -r requirements.txt
code .

In the above script we are performing the following tasks in the sequence.

  • Line 1, 2, 3: Clone Flask tutorials repo and checkout Hello World Flask branch
  • Line 4: Create Virtual Environment
  • Line 5: Activate Virtual Environment
  • Line 6: Upgrade pip
  • Line 7: Install Requirements for requirements.txt
  • Line 8: Opening VS Code IDE. This will automatically load the Flask project with the active directory set to flask-tutorials

Configure Environment for Debugging Flask App with VS Code IDE

In the VS Code IDE, hit the keys Ctrl+Shift+D. It is to Run the Flask App in Debug mode. As we are performing this task for the first time, we will be allowed to choose among two options. One is to Open a file which can be debug or run. Other is the option we are looking for To customize Run and Debug create a launch.json file. Click on create a launch.json file and select a debug configuration that shows up a dropdown with multiple debug configurations. Choose Flask Launch and debug a Flask web application.

Up on choosing Flask from a debug configuration a new file named launch.json in .vscode directory will appear with the following configuration.

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Flask",
            "type": "python",
            "request": "launch",
            "module": "flask",
            "env": {
                "FLASK_APP": "app.py",
                "FLASK_ENV": "development",
                "FLASK_DEBUG": "0"
            },
            "args": [
                "run",
                "--no-debugger",
                "--no-reload"
            ],
            "jinja": true
        }
    ]
}

You can notice the module is flask with the env having default environment variables such as FLASK_APP, FLASK_ENV and FLASK_DEBUG. You can modify these environment variables or add more Flask environment variables in the env section of the launch.json. In case you want to provide custom arguments during debug, you can add it to the args section of launch.json file.

This is one time setup and it is recommended to have the launch.json file checked into the version control such as git that facilitates contributors of the project to help debug easily.

Add break point Flask App in VS Code

Once we have the debug configuration in place at .vscode\launch.json, we will debug Flask application and see the values held by any variable during the run time of the Flask application.

Open the app.py and modify the default route hello to the following.

@app.route('/')
def hello():
    x = 1 + 1
    return 'Hello, World!'

Place the mouse cursor on line that has return statement on line 7 and hit F9 key to add break point. This will show up a red dot to the left of the view. Adding a break point at any place means that we want to stop by that line to see what is the state of the application at this point of time.

You can add multiple break points if you want to see the state of the Flask application at different lines. So also add a break point to the line 6.

Run and Debug a Flask App in VS Code

Now run the Flask app by hitting the F5 function key. The app will be running at http://127.0.0.1:5000/. Once you launch http://127.0.0.1:5000/ in your browser, you will hit the break point that occurs first in the execution flow of the running application. You can go through the next step by hitting F10. Once you are on line 7, hover on x to see the value held by it.This will show the state of variable x with value 2 as the right hand side of the expression 1 + 1 evaluates to 2.

At any point if the line invokes a call to other method within our application and want to debug the underlying method, you can go to the underlying method by hitting F11.

On the Run Window that is available to the left of VS Code window by default, you can see four sections viz Variables, Watch, Call Stack and Breakpoints.

Variables

You can see local and global variables during the execution in the Variables Section and the values they hold at the specific point during the execution. The updated values will be reflected as and when we move through the flow by pressing F10 to pass through further execution steps.

Watch

You can add any variable or methods that you want to have a special attention to in this section by clicking + icon that appears when you hover over the Watch title pane. That’s not all, you can also evaluate python expressions in this section. In such cases this acts as something similar to REPL in addition to watching variables of interest.

Call Stack

In this section you will see the hierarchy or the sequence of callers of the current procedure or routine or method in the hierarchial manner. To understand clearly, you will see the most recent callers to the current method to the top and the older callers which called the caller which called the current method towards the bottom of the hierarchy. Call Stack adds much importance in the aspect of debugging phase and provides much useful information about the sequence of logic that flows in a logic path.

Breakpoints

This section will list all the breakpoints section. This becomes handy when you have several breakpoints across different .py files in the Project.

Stop Debugging

At any point during the debug process, if you are done with the understanding of the execution or troubleshooting the application, you can stop the debugging by pressing Shift+F5

Congratulations 🎉, you have now have a fair understanding of debugging and its importance. You also have mastered debugging a Flask Application in VS Code IDE and how to add watch to variables or methods of choice and learnt about call stack.

Full Source Code of this article can be found here before setup and after setup.

Video Tutorial

Debugging Flask App with Visual Studio Code IDE – TutLinks

Navule Pavan Kumar Rao

I am a Full Stack Software Engineer with the Product Development experience in Banking, Finance, Corporate Tax and Automobile domains. I use SOLID Programming Principles and Design Patterns and Architect Software Solutions that scale using C#, .NET, Python, PHP and TDD. I am an expert in deployment of the Software Applications to Cloud Platforms such as Azure, GCP and non cloud On-Premise Infrastructures using shell scripts that become a part of CI/CD. I pursued Executive M.Tech in Data Science from IIT, Hyderabad (Indian Institute of Technology, Hyderabad) and hold B.Tech in Electonics and Communications Engineering from Vaagdevi Institute of Technology & Science.

Leave a Reply