lin*_*nic 8 visual-studio-code fastapi uvicorn
我正在尝试调试使用 FastAPI (uvicorn) 的应用程序 (web api) 我也在使用诗歌并在 vscode 中设置 projev 虚拟环境。
我读这个教程设置uvicorn和这一个设置vscode但我认为我做的一套东西错了起来。
我尝试将 launch.json 设置为python: module和python: current file
问题似乎是当我运行调试时它无法识别项目结构原因,它在带有此错误的导入语句中停止:
Exception has occurred: ImportError
attempted relative import with no known parent package
Run Code Online (Sandbox Code Playgroud)
这是我当前的 launch.json 配置:
"configurations": [
{
"name": "Python: local debug",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/src/topic_service/service/__init__.py",
"args" : ["--port", "8000"]
},
]
Run Code Online (Sandbox Code Playgroud)
我还尝试添加一个 .env 文件设置 PYTHONPATH:
PYTHONPATH=.:${PYTHONPATH}
Run Code Online (Sandbox Code Playgroud)
我在本地运行应用程序如下:
poetry run uvicorn src.main:app --port 8080 --reload
Run Code Online (Sandbox Code Playgroud)
有谁知道如何正确设置 vscode 来调试 uvicorn 应用程序?
谢谢
更新: 我也试过这篇文章所说的。调试器似乎启动但没有任何反应(没有触发断点)
小智 21
试试这个配置。
{
"name": "Python: Module",
"type": "python",
"request": "launch",
"module": "uvicorn",
"args": ["src.main:app","--reload"]
}
Run Code Online (Sandbox Code Playgroud)
小智 20
对我来说使用这个配置:
在 VSCode 的“调试”部分,选择“创建 launch.json”选项。可能它会像这样在根文件夹资源管理器中的 .vscode 文件夹上打开 launch.json ,在 launch.json 中放置以下内容:
"version": "0.2.0",
"configurations": [
{
"name": "Python: FastAPI",
"type": "python",
"request": "launch",
"module": "uvicorn",
"cwd": "${workspaceFolder}/<folder to your main.py>",
"args": [
"main:app",
"--reload",
"--port", //these arg are optional
"3003"
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
现在,只需运行您的调试器,祝您有美好的一天!
编辑: cwd 确保您的调试器能够找到 main.py 文件的正确路径。因此,对于使用多个调试器或使用外部 vsCode 与 launch.json 的人来说,使用它是一个不错的选择。
nav*_*ule 12
同样,您在 FastAPI 应用程序的开发过程中为uvicorn
模块提供必要的参数,您需要配置您的launch.json
.vscode
使用相应的值所在的目录。
我写了一篇关于自定义项目配置的文章,以在 VS Code 中调试 FastAPI 在这里
假设您发出以下命令以在 uvicorn 服务器上运行 FastAPI,参数如下
uvicorn main:app --reload --port 8000
Run Code Online (Sandbox Code Playgroud)
那么你launch.json
应该有一个值为 of 的模块,uvicorn
并且每个args 都用空格分隔作为args
数组的项目。
"module": "uvicorn",
"type": "python",
"request": "launch",
"args": [
"main:app",
"--reload",
"--port",
"8000"
],
"env": {
"usersecret": "some$Ecret",
}
Run Code Online (Sandbox Code Playgroud)
您可以将这个launch.json
文件放入.vscode
,然后args
根据您的项目结构修改JSON 配置中的数组。
{
// 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: FastAPI",
"type": "python",
"request": "launch",
"module": "uvicorn",
"env": {
"db_username": "postgres",
"db_password": "secret",
"host_server": "localhost",
"database_name": "fastapi",
"ssl_mode": "prefer",
"db_server_port": "5432"
},
"args": [
"main:app",
"--reload",
"--port",
"8000"
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9148 次 |
最近记录: |