Notice
Recent Posts
Recent Comments
Link
250x250
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
Tags
- Baekjoon
- 프로그래머스
- softeer
- 동적계획법
- 자바스크립트
- 오블완
- 너비 우선 탐색
- Lv. 1
- SQL 고득점 KIT
- Lv. 3
- Lv. 0
- LEVEL 2
- Java
- group by
- dfs
- 깊이 우선 탐색
- bfs
- javascript
- level 3
- 파이썬
- 티스토리챌린지
- 소프티어
- DP
- SQL
- Dynamic Programming
- Lv. 2
- Python
- join
- programmers
- 백준
Archives
- Today
- Total
몸과 마음이 건전한 SW 개발자
FastAPI 백엔드 개발 가이드: API 구현 순서와 모던 개발 방법론 [1탄] 본문
728x90
목차
1. 개발 환경 설정
2. 프로젝트 구조 설계
3. database layer 구현
4. api 개발 순서
5. 모던 백엔드 개발 방법론
6. testing 전략
7. 배포 및 운영
1. 개발 환경 설정
가상환경 및 의존성 관리
# Poetry 사용 (권장)
poetry init
poetry add fastapi uvicorn sqlalchemy alembic pydantic
# 또는 pip with requirements.txt
pip install fastapi uvicorn sqlalchemy alembic pydantic
왜 Poetry를 사용하는가?
- 의존성 해결: pip은 의존성 충돌을 해결하지 못하지만, Poetry는 자동으로 해결
- 락 파일: poetry.lock으로 정확한 버전 관리
- 가상환경 통합: 자동으로 가상환경 생성 및 관리
프로젝트 초기 설정
# main.py
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI(
title="API Documentation",
description="RESTful API with FastAPI",
version="1.0.0",
docs_url="/docs",
redoc_url="/redoc"
)
# CORS 설정
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # 운영환경에서는 특정 도메인만 허용
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
2. 프로젝트 구조 설계
Layered Architecture (권장)
project/
├── app/
│ ├── core/ # 핵심 설정 및 공통 기능
│ │ ├── config.py # 환경 변수, 설정
│ │ ├── database.py # DB 연결 설정
│ │ ├── security.py # 인증/인가
│ │ └── exceptions.py # 커스텀 예외
│ ├── domain/ # 도메인별 모듈
│ │ └── users/
│ │ ├── controllers/ # API 엔드포인트
│ │ ├── services/ # 비즈니스 로직
│ │ ├── repositories/ # 데이터 액세스
│ │ ├── schemas/ # Pydantic 모델
│ │ └── models/ # SQLAlchemy 모델
│ ├── shared/ # 공통 유틸리티
│ │ ├── utils.py
│ │ └── constants.py
│ └── main.py
├── tests/
├── migrations/ # Alembic 마이그레이션
├── docker-compose.yml
├── Dockerfile
└── pyproject.toml # Poetry 설정
왜 이런 구조를 사용하는가?
- Domain-Driven Design (DDD) 접근
- 도메인 분리: 각 비즈니스 도메인이 독립적으로 관리됨
- 의존성 역전: Repository 패턴으로 데이터베이스 의존성 분리
- 테스트 용이성: 각 레이어를 독립적으로 테스트 가능
Layered Architecture 이유
- Controller Layer: HTTP 요청/응답 처리만 담당
- Service Layer: 비즈니스 로직 집중, 트랜잭션 관리
- Repository Layer: 데이터 액세스 추상화
- Model Layer: 데이터 구조 정의
3. Database Layer 구현
1. Database 설정
# app/core/database.py
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
DATABASE_URL = "sqlite:///./app.db"
engine = create_engine(
DATABASE_URL,
poolclass=StaticPool, # SQLite용
connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
def get_db():
"""의존성 주입용 DB 세션"""
db = SessionLocal()
try:
yield db
finally:
db.close()
2. SQLAlchemy Models
# app/domain/users/models/user.py
from sqlalchemy import Column, Integer, String, DateTime, Boolean
from sqlalchemy.sql import func
from app.core.database import Base
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
email = Column(String, unique=True, index=True, nullable=False)
username = Column(String, unique=True, index=True, nullable=False)
hashed_password = Column(String, nullable=False)
is_active = Column(Boolean, default=True)
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
3. Alembic 마이그레이션 설정
# 초기 설정
alembic init migrations
# 마이그레이션 파일 생성
alembic revision --autogenerate -m "Create users table"
# 마이그레이션 실행
alembic upgrade head
왜 Alembic을 사용하는가?
- 스키마 버전 관리: 데이터베이스 스키마 변경사항 추적
- 팀 협업: 모든 개발자가 동일한 스키마 상태 유지
- 배포 안전성: 운영 환경에서 안전한 스키마 업데이트
728x90
'백엔드' 카테고리의 다른 글
FastAPI 백엔드 개발 가이드: API 구현 순서와 모던 개발 방법론 [3탄] (3) | 2025.08.12 |
---|---|
FastAPI 백엔드 개발 가이드: API 구현 순서와 모던 개발 방법론 [2탄] (0) | 2025.08.12 |