Hello World!

[FastAPI] Best Practices - Project Structure

by PyTong

BE

Project Structure

FastAPI 프로젝트 구조 설계 할때 참고하기 좋다.

Netflaix/Dipatch를 참조하여 수정한 자료이다.

fastapi-project
├── alembic/
├── app # 원본은 src 이지만 본인은 app 선호함.
│   ├── auth
│   │   ├── router.py
│   │   ├── schemas.py  # pydantic models
│   │   ├── models.py  # db models
│   │   ├── dependencies.py
│   │   ├── config.py  # local configs
│   │   ├── constants.py
│   │   ├── exceptions.py
│   │   ├── service.py
│   │   └── utils.py
│   ├── aws
│   │   ├── client.py  # client model for external service communication
│   │   ├── schemas.py
│   │   ├── config.py
│   │   ├── constants.py
│   │   ├── exceptions.py
│   │   └── utils.py
│   └── posts
│   │   ├── router.py
│   │   ├── schemas.py
│   │   ├── models.py
│   │   ├── dependencies.py
│   │   ├── constants.py
│   │   ├── exceptions.py
│   │   ├── service.py
│   │   └── utils.py
│   ├── config.py  # global configs
│   ├── models.py  # global models
│   ├── exceptions.py  # global exceptions
│   ├── pagination.py  # global module e.g. pagination
│   ├── database.py  # db connection related stuff
│   └── main.py
├── tests/
│   ├── auth
│   ├── aws
│   └── posts
├── templates/
│   └── index.html
├── requirements
│   ├── base.txt
│   ├── dev.txt
│   └── prod.txt
├── .env
├── .gitignore
├── logging.ini
└── alembic.ini

프로젝트가 확장될 것을 염두하여, 도메인 별로 구조를 가져간다 ( crud, router, models 로 나누는 것이 아닌)

 

1. 모든 도메인 디렉토리를 app/ 안에 저장한다.

  • app/- 앱의 최상위 디렉토리로, 일반적인 모델, 설정, 상수 등을 포함한다.
  • app/main.py- FastAPI 앱을 초기화하는 프로젝트의 루트

 

2. 각 패키지에는 라우터, 스키마, 모델 등이 있다.

  • router.py- 모든 엔드포인트를 갖춘 각 모듈의 핵심
  • schemas.py- pydantic 모델용
  • models.py- db 모델용
  • service.py- 모듈별 비즈니스 로직
  • dependencies.py- 라우터 종속성
  • constants.py- 모듈별 상수 및 오류 코드
  • config.py- 예: 환경 변수
  • utils.py- 비즈니스 로직이 아닌 기능, 예: 응답 정규화, 데이터 보강 등
  • exceptions.py- 모듈별 예외, 예 PostNotFound:InvalidUserData

 

3. 다른 패키지에서 (서비스, 상수) 등이 필요한 경우 명시적으로 모듈 이름으로 가져온다.

from src.auth import constants as auth_constants
from src.notifications import service as notification_service
from src.posts.constants import ErrorCode as PostsErrorCode  # PostsErrorCode로 가져온다.

 

출처

 

GitHub - zhanymkanov/fastapi-best-practices: FastAPI Best Practices and Conventions we used at our startup

FastAPI Best Practices and Conventions we used at our startup - zhanymkanov/fastapi-best-practices

github.com

 

블로그의 정보

PyTong

PyTong

활동하기