Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debug FastAPI application in VSCode

i'm trying to debug an application (a web api) that use FastAPI (uvicorn) I'm also using poetry and set the projev virtual environment in vscode.

i read this tutorial to setup uvicorn and this one to setup vscode but i think i'm doing something wrong in set it up.

I tried to setup the launch.json both as python: module and python: current file

The problem seems that it doesn't recognize the project structure cause when i run the debug it stopped in an import statement with this error:

Exception has occurred: ImportError
attempted relative import with no known parent package

This is my current launch.json configuration:

"configurations": [
    {
        "name": "Python: local debug",
        "type": "python",
        "request": "launch",
        "program": "${workspaceFolder}/src/topic_service/service/__init__.py",
        "args" : ["--port", "8000"]
    },
]

I also tried to add a .env file setting PYTHONPATH:

PYTHONPATH=.:${PYTHONPATH}

Locally i run the application as follow:

poetry run uvicorn src.main:app --port 8080 --reload

Does anyone know how to correctly setup vscode to debug an uvicorn application?

Thank you

UPDATE: I also tried what this article says. the debugger seems to start but nothing happen (no breakpoint is triggered)

like image 487
linnic Avatar asked Feb 13 '20 09:02

linnic


People also ask

How do I Debug an app in VS Code?

To bring up the Run and Debug view, select the Run and Debug icon in the Activity Bar on the side of VS Code. You can also use the keyboard shortcut Ctrl+Shift+D. The Run and Debug view displays all information related to running and debugging and has a top bar with debugging commands and configuration settings.

How do I get Debug option in Visual Studio?

To set Visual Studio debugger options, select Tools > Options, and under Debugging select or deselect the boxes next to the General options. You can restore all default settings with Tools > Import and Export Settings > Reset all settings.


2 Answers

Try this configuration.

{
    "name": "Python: Module",
    "type": "python",
    "request": "launch",
    "module": "uvicorn",
    "args": ["src.main:app","--reload"]
}
like image 127
John Lien Avatar answered Sep 22 '22 05:09

John Lien


The quick and easy way: launch debugger F5 and then select FastAPI Debug Configuration: (p.s. this works on the VSCode Insiders; haven't tried it on a regular version)

enter image description here

like image 35
Neil Avatar answered Sep 22 '22 05:09

Neil