VSCode 和 FastAPI 调试 - 不会中断路由

SS *_*hah 5 python visual-studio-code vscode-debugger fastapi

刚刚开始使用 FastAPI,但在尝试让它识别 VSCode 调试器中的断点时遇到了问题。奇怪的是,它确实成功地打破了路线中未包含的线路

直接从教程中提取: https: //fastapi.tiangolo.com/tutorial/debugging/

import uvicorn
from fastapi import FastAPI

app = FastAPI()  # breakpoint here works on launching file
print('here')    # breakpoint here works on launching file


@app.get("/")
def root():
    a = "a"   # breakpoint here does NOT work
    b = "b" + a
    return {"hello world": b}  # returns data successfully


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=5002)
Run Code Online (Sandbox Code Playgroud)

如上所述,路由外的线路工作正常,当我转到该地址时,我成功获取数据,但路由内的断点不会触发。不知道我在这里缺少什么。尝试过VSCode 中的 Debug FastAPI 应用程序的各种解决方案

我不确定这是否会产生影响,但这也是通过 VSCode 上的远程 SSH 扩展运行的(我的代码位于 gcloud 虚拟机上)。也许这有所贡献,但同样,其他断点也可以正常触发。

我的启动.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: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

编辑:看起来如果我用“async def”替换“def”,它确实可以工作,尽管我试图让它与 SQLite DB 一起使用,并且按照此页面: https: //fastapi.tiangolo.com/tutorial/ sql-databases/它建议默认使用“def”(带有配置为使用 async def 的选项)。我需要进一步研究其中的区别。

Jil*_*eng 0

原因是root()代码中虽然定义了方法“ ”,但是我们并没有在代码中调用这个方法。调试时,调试器没有执行方法中的代码。

root()请尝试在代码中添加调用方法“ ”的语句:

在此输入图像描述

  • 感谢您抽出时间,但这不是我要找的。我正在寻找的是当用户请求 URL 时,断点会触发。如果我在浏览器中访问 http://localhost:5002/,它会执行该方法,因为我得到了预期的响应 ({"hello world": 'ba'}),但它不会在断点。当我使用 Flask 时,它会在触发请求时按照预期执行行为。我想如果我想调试特定参数,我可以创建一个文件来调用该函数,但这似乎是一种迂回的方法。 (3认同)
  • @SSShah没关系,我找到了我的问题。这是因为我在我试图断点的路线上方定义了一条类似的路线。所以它就去了那里。 (2认同)