Skip to content

FastAPI용 VSCode 설정

venv 생성

여기로 부터,

Note:
venv를 사용하면 여러 프로젝트에 대해 각각 패키지 설치를 관리할 수 있다. 기본적으로 "가상으로" 격리된 Python을 설치하고 해당 설치에 패키지를 설치할 수 있다.

프로젝트마다 서로 다른 버전의 서로 다른 패키지가 필요하기 때문에 많은 언어에서 venv를 사용하는 것은 매우 일반적인 관행이며, 이 모든 것을 글로벌 수준에서 관리하는 것은 재앙을 초래할 수 있다.

특정 Python 버전의 바이너리로 venv를 만들면 시스템 버전에 관계없이 다양한 버전의 Python을 실행할 수 있다.

# To install a venv in your project, go to your project directory and run the following
python3 -m venv .venv

# This command will create a .venv folder which will contain the python 
# binaries and packages for you project

# to install a specifc python version run the following
virtualenv .venv --python=python3.9

# now the venv needs to be activated, to do so run
source .venv/bin/activate

디버거 설정

FastAPI 앱을 실행하도록 설정된 디버거를 설정하려면 .vscode/launch.json 파일에 다음을 추가한다.

# .vscode/launch.json
# assuming that the path to your FastAPI app file is at src/app/main.py.
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Python: Module",
      "type": "python",
      "request": "launch",
      "module": "src.app.main",
      "env": { "PYTHONPATH": "${workspaceFolder}/src/" }
    }
  ]
}

이제 디버거로 이동하면 디버거가 연결된 상태에서 서버를 시작할 수 있는 옵션이 있으며, 이를 통해 breakpoint을 사용할 수 있다.

기본 설정

# .vscode/settings.json
{
  "[python]": {
    "editor.defaultFormatter": "ms-python.autopep8"
  },
  "python.testing.pytestArgs": ["."],
  "python.testing.pytestEnabled": true,
  "python.terminal.activateEnvironment": true
}

이 설정에 대한 설명은 다음과 같다.

  • 테스트 프레임워크로 pytest를 설정
  • 모든 테스트 파일을 검색하고 테스트 탭에서 테스트를 실행할 수 있다.
  • VSCode 터미널에서 venv를 자동으로 활성화한다.
  • autopep8을 포매터로 설정한다 (작동하려면 autopep8 확장자를 설치해야 함).

팀을 위한 공통 확장 프로그램 설정

팀원 모두 동일한 도구를 사용하고 있는지 확인하려면 사용 중인 확장자를 .vscode/extensions.json에 추가하면 된다.

# .vscode/extensions.json
{
  "recommendations": ["ms-python.autopep8"]
}