Debug a Flask (Python) web application in Visual Studio Code

后端 未结 8 1884
失恋的感觉
失恋的感觉 2020-12-11 04:28

How do I configure Visual Studio Code to debug a Flask (Python) web application?

For example, when I set the debugger in the view function, it should allow me to step

相关标签:
8条回答
  • 2020-12-11 05:15

    I don't use Visual Studio Code for Python development. However, Flask has a really nice debugging option, that allows you to debug from a browser. This is not a solution for Visual Studio Code, but a workaround.

    When you define your application, pass the debug = true parameter to enable debugging mode. Then you can debug your code from the browser.

    app = Flask(__name__)
    app.config['DEBUG'] = True
    

    More information can be found here.

    0 讨论(0)
  • 2020-12-11 05:18
    1. Create startup.py in your project root directory with the following code

       # Needed to start the debugger for the Flask application in the Visual Studio Code IDE
       import sys
       import re
       from flask.cli import main
       sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
       sys.exit(main())
      
    2. Update the launch.json file in Visual Studio Code by browsing to the Debug tab (Left pane), and then click on the settings icon (Gear icon). Scroll down to the "FLASK" section:

      a) Change "program" value to "${workspaceRoot}/startup.py"

      b) Change "FLASK_APP" value to "${workspaceRoot}/run.py" (or whatever your main entry point file is"

    3. Go to menu FilePreferencesSettings, and then click on workspace settings in the top right corner. Insert the following field: "python.pythonPath": "${workspaceRoot}/venv/Scripts/python.exe" (If your virtual environment is named something other than venv then replace it with the appropriate value.)

    0 讨论(0)
提交回复
热议问题