Study/fastapi

vscode, cusor ai에서 fastapi debug 하는 방법 with launch.json

bluebamus 2025. 2. 19.

1. launch.json 기본 구조

   - 해당 파일의 위치는 프로젝트 내 .vscode/launch.json가 된다.

   - launch.json 파일은 VSCode의 디버깅 구성을 정의하는 핵심 파일입니다. 기본 구조는 다음과 같다.

{
    "version": "0.2.0",
    "configurations": [
        {
            // 각각의 디버그 구성이 여기에 위치
        }
    ]
}

 

   - 현재 vscode, cosur ai에 적용중인 설정

{
    // 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": "debugpy",
            "request": "launch",
            "module": "uvicorn",
            "args": [
                "main:app",
                "--host",
                "127.0.0.1",
                "--port",
                "8000",              
            ],
        },
    ]
}

 

2. 공통 Configuration 속성

   - 모든 디버그 구성에서 사용할 수 있는 주요 속성들이다.

 

   1) 기본 속성

      - version : 템플릿 버전으로, 제시된 고정 값을 사용하면 된다.

      - name: 디버그 구성의 이름 (필수), vscode의 디버그 스크롤 메뉴에 노출된다.
      - type: 디버그 타입이다. debugpy는 파이썬을 디버깅 할때 사용한다.
      - request: launch 와 attach 옵션이 있다. 로컬에서 디버거를 실행하는 목적인 경우에는 launch 를 사용하고, attach 의 경우는 원격에서 ssh 등으로 붙었을 때 사용할 수 있는 옵션이다.( docker 로 띄웠을 때도 붙는데 사용한다.)

      - module : python -m uvicorn 과 동일하다. 현재 활성화된 Python 환경의 모듈로 지정한 모듈을 실행한다.
         - 만약 main.py 등으로 실행하고자 한다면 파이썬 스크립트를 실행하는 program 속성을 사용한다.
      - args : module에 제공되는 인자들을 나열한다.
      - presentation: UI 표시 방식 설정

"presentation": {
    "hidden": false,
    "group": "development",
    "order": 1
}

 

   2) 환경 관련 속성

      - env: 환경 변수 설정
      - envFile: 환경 변수 파일 경로
      - cwd: 작업 디렉토리 설정

 

   3) 콘솔 관련 속성

      - console: 콘솔 유형 (internalConsole, integratedTerminal, externalTerminal)
      - serverReadyAction: 서버 준비 상태 감지 설정
      - outputCapture: 출력 캡처 방식 (console, std)

 

3. Python 특화 Configuration 속성

   - Python 디버깅에서 사용되는 특별한 속성들이다.

 

   1) Python 패스 및 인터프리터

      - python: Python 인터프리터 경로

      - pythonPath: 대체 Python 경로 (deprecated)

      - PYTHONPATH: Python 모듈 검색 경로

 

   2) 디버깅 옵션

      - stopOnEntry: 시작 시 즉시 중단
      - justMyCode: 사용자 코드만 디버깅
      - django: Django 디버깅 활성화
      - jinja: Jinja 템플릿 디버깅 활성화

 

4. Django 디버깅 설정

   1) 기본 Django 설정

{
    "name": "Django Debug",
    "type": "python",
    "request": "launch",
    "program": "${workspaceFolder}/manage.py",
    "args": ["runserver"],
    "django": true,
    "justMyCode": true,
    "env": {
        "DJANGO_SETTINGS_MODULE": "project.settings.development"
    }
}

 

   2) Django 테스트 디버깅 설정

{
    "name": "Django Test",
    "type": "python",
    "request": "launch",
    "program": "${workspaceFolder}/manage.py",
    "args": ["test", "app_name.tests.test_file"],
    "django": true,
    "justMyCode": false,
    "env": {
        "DJANGO_SETTINGS_MODULE": "project.settings.test"
    }
}

 

5. FastAPI 디버깅 설정

   1) 기본 FastAPI 설정

      - --reload 옵션을 사용하면 안된다.

{
    "name": "FastAPI Debug",
    "type": "python",
    "request": "launch",
    "module": "uvicorn",
    "args": [
        "main:app",
        "--reload",
        "--port",
        "8000"
    ],
    "jinja": true,
    "justMyCode": true
}

 

   2) 만약 main.py 등의 파일로 실행한다면 다음과 같이 수정

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Python Debugger: FastAPI",
      "type": "debugpy",
      "request": "launch",
      "program": "main.py",
      ...
    }
  ]
}

 

   3) docker로 실행시 다음과 같이 설정

# Dockerfile
...
# 도커에 debugpy 설치
RUN uv pip install --system -r /app/requirements.txt && \
    pip install debugpy 
...
version: '3.8'

services:
  backend:
    ports:
      - "5678:5678"     # debugpy port 노출
      
    # 기존 서버 실행자 앞에 debugpy 실행하고 port 설정
    command: ["python", "-m", "debugpy", "--listen", "0.0.0.0:5678", "--wait-for-client",
              "-m", "uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"]
    env_file:
      - .env.dev
    volumes:
      - .:/app

 

      - launch.json 의 request 는 launch 가 아닌 attach 로 설정하고, 연결 설정한다.

// launch.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 Debugger: Docker FastAPI",
            "type": "debugpy",
            "request": "attach",
            "connect": {
                "host": "localhost",
                "port": 5678
            },
            "pathMappings": [
                {
                    "localRoot": "${workspaceFolder}",
                    "remoteRoot": "/app"
                }
            ],
        }
    ]
}

 

   4) FastAPI 테스트 디버깅 설정

{
    "name": "FastAPI Test",
    "type": "python",
    "request": "launch",
    "module": "pytest",
    "args": [
        "tests/",
        "-v"
    ],
    "justMyCode": false
}

 

6. 여러개의 debug 설정 구성

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Django",
            "type": "python",
            "request": "launch",
            "program": "${workspaceFolder}/manage.py",
            "args": [
                "runserver",
                "--noreload"
            ],
            "django": true,
            "env": {
                "DJANGO_SETTINGS_MODULE": "myproject.settings"
            }
        },
        {
            "name": "Python: FastAPI",
            "type": "python",
            "request": "launch",
            "module": "uvicorn",
            "args": [
                "app.main:app",
                "--reload"
            ],
            "cwd": "${workspaceFolder}",
            "debugOptions": [
                "RedirectOutput"
            ]
        }
    ]
}

 

7. 고급 디버깅 옵션

   1) 디버그 제어 속성

      - stopOnEntry: 프로그램 시작 시 첫 번째 라인에서 자동으로 중단합니다. 초기 상태 검사에 유용하다.
      - breakOnLoad: 파일이 로드될 때 자동으로 중단점을 설정합니다. 동적 로딩 시 유용하다.
      - showAsyncStacks: 비동기 호출 스택을 표시합니다. 비동기 코드 디버깅에 필수적이다.

 

   2) 소스맵 관련 속성

      - sourceMapPathOverrides: 소스맵 경로를 실제 파일 시스템 경로로 매핑한다.

"sourceMapPathOverrides": {
    "webpack:///./~/*": "${workspaceFolder}/node_modules/*",
    "webpack:///src/*": "${workspaceFolder}/src/*"
}

 

   3) 디버그 출력 제어

      - redirectOutput: 프로그램 출력을 디버그 콘솔로 리디렉션한다.
      - outputCapture: 출력 캡처 방식을 지정한다.
         - console: 콘솔 API 호출만 캡처

         - std: 표준 출력/오류 스트림 캡처

 

   4) debugOptions 설정

      - debugOptions 배열을 사용하여 세밀한 디버깅 동작을 제어할 수 있다.

{
    "name": "Advanced Debug Configuration",
    "type": "python",
    "request": "launch",
    "program": "${file}",
    "debugOptions": [
        "RedirectOutput",
        "BreakOnLoad",
        "ShowAsyncStacks",
        "DjangoDebugging"
    ]
}

 

      1. 주요 debugOptions 값들:

         - RedirectOutput: 모든 프로그램 출력을 VSCode 디버그 콘솔로 리디렉션
         - BreakOnLoad: 모듈 로드 시점에 중단점 활성화
         - ShowAsyncStacks: 비동기 호출 스택 추적 활성화
         - Django / Flask / Jinja: 특정 프레임워크 디버깅 지원 활성화
         - DebugStdLib: 표준 라이브러리 코드 디버깅 허용
         - Sudo: 관리자 권한으로 디버깅 실행 (Unix 시스템)

 

- reference : 

https://velog.io/@jomminii/debugger

 

debugger - 10분 배우고 하루 30분 벌자

print, console.log로 디버그를 해왔던 과거를 잊어라. 이젠 디버거!

velog.io

https://tutlinks.com/debug-fastapi-in-vs-code-ide/

 

Debug FastAPI in VS Code IDE » TutLinks

In this tutorial we will setup Visual Studio Code IDE to help debug FastAPI repository. Analyse the state of variables and see how to debug FastAPI in VS Code. To do this we will add a debug configuration and create a breakpoint in a sample FastAPI reposit

tutlinks.com

 

댓글