You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyCharm中FastAPI配置正常运行,添加断点调试时卡顿

PyCharm调试FastAPI(Poetry环境)添加断点后卡顿无法启动的问题及解决办法

问题背景

使用Poetry创建Python项目,配置及代码如下。命令行或PyCharm普通运行均可正常启动FastAPI服务,无断点时调试也能正常启动,但只要添加任意断点,PyCharm就会一直卡顿,API服务无法启动完成,端点也无法访问。

项目配置(pyproject.toml)

[tool.poetry]
name = "my-app"
version = "0.1.0"
description = ""
authors = ["me"]
readme = "README.md"

[tool.poetry.dependencies]
python = "^3.12"
fastapi = "^0.104.1"
supabase = "^2.0.3"
uvicorn = "^0.24.0.post1"
pydantic = {extras = ["dotenv"], version = "^1.10.2"}

[tool.poetry.group.dev.dependencies]
mypy = "^1.5.1"
pre-commit = "^3.5.0"
pytest = "^7.4.3"
pytest-cov = "^4.1.0"

项目代码

  • 入口文件web_server.py:
import uvicorn
from app.config.rest.api import create_fastapi_app

app = create_fastapi_app()

if __name__ == "__main__":  
    uvicorn.run(app)
  • api.py:
from fastapi import FastAPI

from app.config.rest.endpoints.router import api_router


def create_fastapi_app() -> FastAPI:
    app = FastAPI(title="My API")

    app.include_router(api_router, prefix="/api")

    return app
  • router.py:
from fastapi import Header, APIRouter, Depends

from app.config.rest.endpoints.meta import router as meta_router


def custom_headers(
        user_id: str = Header(examples=["postman"], convert_underscores=False),
):
    return


no_headers_router = APIRouter()
headers_router = APIRouter(dependencies=[Depends(custom_headers)])
no_headers_router.include_router(meta_router, tags=["meta"])

api_router = APIRouter()
api_router.include_router(no_headers_router)
api_router.include_router(headers_router)

启动命令:poetry run uvicorn --app-dir ./src app.web_server:app --reload

可能的原因及解决办法

  • Python 3.12与PyCharm调试器兼容性问题
    Python 3.12属于较新版本,旧版PyCharm对其调试支持存在兼容性bug。直接升级PyCharm到2023.3及以上版本,该版本开始完善对Python 3.12的调试适配。

  • Uvicorn重载模式与调试器冲突
    启动命令中的--reload会让Uvicorn启动子进程实现热重载,PyCharm调试器无法正确附着到子进程,进而导致卡顿。调试时去掉该参数:
    把启动命令改为poetry run uvicorn --app-dir ./src app.web_server:app,或者在PyCharm运行配置的Additional arguments中删除--reload。

  • Poetry虚拟环境路径映射异常
    PyCharm可能未正确识别Poetry创建的虚拟环境,导致断点解析时路径匹配出错引发卡顿。手动指定虚拟环境:

    1. 打开File > Settings > Project: my-app > Python Interpreter
    2. 点击齿轮图标选择Add,切换到Poetry Environment选项卡,选中当前项目对应的虚拟环境,确认后重启PyCharm。
  • 断点位置不合理
    如果断点设置在create_fastapi_app、路由初始化这类服务启动阶段的代码上,FastAPI初始化时的依赖解析会频繁触发调试器中断,导致卡顿。尝试将断点移到具体的接口处理函数(比如meta_router下的接口逻辑)中,避开启动流程代码。

内容的提问来源于stack exchange,提问作者Samer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 02:05:16