fast api+python 유용한 보조 라이브러리

jinhan han·2025년 6월 12일
0

풀스택 개발 세팅

목록 보기
4/4
post-thumbnail

Fastapi+파이썬에서 사용되면 좋은 라이브러리들을 소개해보겠다.

1.코드 포매팅, 2.코드 분석, 3.보안, 4.성능 분석, 5.테스팅, 6.의존성 관리

1.코드 포매팅

pip install black

목적 : "하나의 명확한 방법"으로 코드 포맷을 표준화
사용 용도 : 파이썬 코드를 일관된 스타일로 자동 포매팅
사용시 장점 :

  • 코드 스타일 일관성 보장
  • 코드 리뷰 시 스타일 관련 논의 제거
  • 개발자 간 스타일 통일

사용 예시 :

""" 파이썬 해당 파일만 포매팅 할때 """ 
black my_script.py
""" 디렉토리 전체 포매팅 할때""" 
black src/
"""   설정 파일 (pyproject.toml) """ 
[tool.black]
line-length = 88
target-version = ['py39']

출력 예시 :

적용 전

user_info={'name':'김철수','age':25,'skills':['python','django','react']}
filtered_skills=[skill.upper() for skill in user_info['skills'] if len(skill)>5]
print(f"User: {user_info['name']}, Skills: {', '.join(filtered_skills)}")

적용 후

user_info = {"name": "김철수", "age": 25, "skills": ["python", "django", "react"]}
filtered_skills = [
    skill.upper() for skill in user_info["skills"] if len(skill) > 5
]
print(f"User: {user_info['name']}, Skills: {', '.join(filtered_skills)}")

2.코드 분석

pip install ruff

목적 : 모든 코드 품질 검사를 하나의 빠른 도구로 통합
사용 용도 : 파이썬 코드의 스타일, 버그, 복잡성을 초고속으로 분석
사용시 장점 :

  • 기존 도구 대비 10-100배 빠른 속도
  • flake8, pylint, isort 등 여러 도구 기능 통합
  • 자동 수정 기능 제공

사용 예시 :

""" 코드 검사 """
ruff check .
""" 자동 수정 """
ruff check --fix .
""" 설정 파일 (pyproject.toml) """
[tool.ruff]
line-length = 88
select = ["E", "F", "W", "B", "I"]

출력 예시 :

src/main.py:12:1: F401 [*] sys imported but unused
src/main.py:23:80: E501 Line too long (95 > 88 characters)
src/main.py:45:1: I001 [*] Import block is un-sorted or un-formatted
Found 3 errors (2 fixable with --fix)

pip install pylint

목적 : 코드 품질의 종합적 평가 및 개선점 제시
사용 용도 : 코드 품질, 스타일, 잠재적 버그를 종합적으로 분석
사용시 장점 :

  • 매우 상세한 코드 분석
  • 코드 점수 및 등급 제공
  • 커스텀 체커 개발 가능

사용 예시 :

""" 파일 분석 """
pylint my_script.py
""" 설정 파일 생성 """
pylint --generate-rcfile > .pylintrc

출력 예시 :

************* Module main
main.py:1:0: C0114: Missing module docstring (missing-module-docstring)
main.py:5:0: C0116: Missing function or method docstring (missing-function-docstring)
main.py:12:4: W0613: Unused argument 'args' (unused-argument)
Your code has been rated at 7.50/10

3.보안

pip install bandit

목적 : 코드 레벨에서의 보안 위험 사전 제거
사용 용도 : 파이썬 코드에서 보안 취약점을 자동으로 탐지
사용시 장점 :

  • 일반적인 보안 취약점 자동 탐지
  • OWASP Top 10 기반 검사
  • CI/CD 파이프라인 통합 가능

사용 예시 :

# 보안 스캔
bandit -r src/
# JSON 리포트 생성
bandit -r src/ -f json -o security_report.json

출력 예시 :

> Issue: [B105:hardcoded_password_string] Possible hardcoded password: 'admin123'
   Severity: Medium   Confidence: Medium
   Location: ./src/config.py:15

pip install safety

목적 : 서드파티 패키지의 보안 위험 관리
사용 용도 : 설치된 패키지들의 알려진 보안 취약점 검사
사용시 장점 :

  • 실시간 보안 데이터베이스 연동
  • requirements.txt 기반 자동 검사
  • 취약점 심각도별 분류

사용 예시 :

# 현재 환경 검사
safety check
# requirements.txt 검사
safety check -r requirements.txt

출력 예시 :

╒══════════════════════════════════════════════════════════════════════════════╕
│ found 2 known security vulnerabilities in 156 packages                      │
╘══════════════════════════════════════════════════════════════════════════════╛
╒══════════════════════════════════════════════════════════════════════════════╕
│ VULNERABILITY ID: 42194                                                     │
│ PACKAGE NAME: urllib3                                                       │
│ INSTALLED VERSION: 1.25.6                                                   │
│ AFFECTED VERSIONS: <1.26.5                                                  │
│ VULNERABILITY: CVE-2021-33503                                               │
╘══════════════════════════════════════════════════════════════════════════════╛

4.성능 분석

pip install py-spy

목적 : 성능 병목 지점의 정확한 식별
사용 용도 : 실행 중인 파이썬 프로세스의 성능을 실시간으로 프로파일링
사용시 장점 :

  • 코드 수정 없이 프로파일링 가능
  • 프로덕션 환경에서도 안전하게 사용
  • 플레임 그래프 시각화 제공

사용 예시 :

# 실행 중인 프로세스 프로파일링
py-spy record -o profile.svg --pid 12345
# 스크립트 실행과 동시에 프로파일링
py-spy record -o profile.svg -- python my_script.py

출력 예시 :

Sampling process 100 times a second. Press Control-C to exit.
Total Samples 1000
GIL: 89.00%, Active: 11.00%, Threads: 1
  %Own   %Total  OwnTime  TotalTime  Function (filename:line)
  89.00%  89.00%   0.89s     0.89s   slow_function (main.py:15)
   8.00%  97.00%   0.08s     0.97s   main (main.py:5)

python -m cProfile -s cumulative

목적 : 함수 레벨에서의 성능 병목 식별
사용 용도 : 파이썬 내장 프로파일러로 함수별 실행 시간 분
사용시 장점 :

  • 별도 설치 불필요 (파이썬 내장)
  • 정확한 함수 호출 통계 제공
  • 다양한 정렬 옵션 제공

사용 예시 :

# 스크립트 프로파일링
python -m cProfile -s cumulative my_script.py
# 결과를 파일로 저장
python -m cProfile -o profile.stats my_script.py

출력 예시 :

 ncalls  tottime  percall  cumtime  percall filename:lineno(function)
     16/1    0.000    0.000   43.451   43.451 {built-in method builtins.exec}
        1    0.000    0.000   43.451   43.451 my_script.py:1(<module>)
        1    0.000    0.000   43.424   43.424 my_script.py:518(main)
        1    0.000    0.000   42.251   42.251 my_script.py:396(run)
        6   39.477    6.579   39.477    6.579 {built-in method builtins.input}

5.테스팅

pip install pytest

목적 : 코드 품질 보장 및 리그레션 방지
사용 용도 : 파이썬 코드의 단위 테스트, 통합 테스트 작성 및 실행
사용시 장점 :

  • 간결한 테스트 코드 작성
  • 강력한 fixture 시스템
  • 풍부한 플러그인 생태계

사용 예시 :

# 테스트 실행
pytest
# 커버리지와 함께 실행
pytest --cov=src tests/

출력 예시 :

================================= test session starts =================================
platform darwin -- Python 3.9.7, pytest-7.1.2, pluggy-1.0.0
rootdir: /Users/project
plugins: cov-3.0.0
collected 8 items
tests/test_main.py::test_add_function PASSED                              [ 12%]
tests/test_main.py::test_subtract_function PASSED                         [ 25%]
tests/test_utils.py::test_validate_input PASSED                           [ 37%]
tests/test_utils.py::test_process_data FAILED                             [ 50%]
tests/test_api.py::test_get_user PASSED                                   [ 62%]
tests/test_api.py::test_create_user PASSED                                [ 75%]
tests/test_api.py::test_delete_user PASSED                                [ 87%]
tests/test_integration.py::test_full_workflow PASSED                      [100%]
================================== FAILURES ===================================
_________________________ test_process_data ________________________
    def test_process_data():
        result = process_data([1, 2, 3])
      assert result == [2, 4, 6]
E       assert [1, 4, 9] == [2, 4, 6]
E         At index 0 diff: 1 != 2
tests/test_utils.py:15: AssertionError
========================= short test summary info ==========================
FAILED tests/test_utils.py::test_process_data - assert [1, 4, 9] == [2, 4, 6]
========================= 1 failed, 7 passed in 0.12s =========================

pip install coverage

목적 : 테스트의 완성도 평가
사용 용도 : 테스트가 코드의 어느 부분을 실행했는지 측정
사용시 장점 :

  • 정확한 커버리지 측정
  • HTML 리포트 생성
  • 브랜치 커버리지 지원

사용 예시 :

# 커버리지 실행
coverage run -m pytest
coverage report
coverage html

출력 예시 :

Name                 Stmts   Miss  Cover   Missing
--------------------------------------------------
src/__init__.py          0      0   100%
src/main.py             45      3    93%   78-80
src/utils.py            32      8    75%   45-52, 67
src/api.py              28      0   100%
src/database.py         67     15    78%   89-95, 102-108, 125
--------------------------------------------------
TOTAL                  172     26    85%
Coverage HTML written to dir htmlcov

6.의존성 관리

curl -sSL https://install.python-poetry.org | python3 -

목적 : 프로젝트 의존성의 체계적 관리
사용 용도 : 파이썬 프로젝트의 의존성 관리 및 패키징
사용시 장점 :

  • 의존성 해결 알고리즘으로 충돌 방지
  • 가상환경 자동 관리
  • 배포용 패키지 빌드 지원

사용 예시 :

""" 설치 """
curl -sSL https://install.python-poetry.org | python3 -
""" 새 프로젝트 생성 """
poetry new my-project
""" 의존성 설치 """
poetry add requests
poetry add pytest --group dev
profile
개발자+분석가+BusinessStrategist

0개의 댓글