|
| 1 | +# 코드 스타일 및 규칙 |
| 2 | + |
| 3 | +## 네이밍 규칙 |
| 4 | +- **변수/함수/메서드**: `snake_case` |
| 5 | +- **클래스**: `PascalCase` |
| 6 | +- **상수**: `UPPER_SNAKE_CASE` |
| 7 | +- **비공개 메서드/속성**: `_leading_underscore` |
| 8 | + |
| 9 | +## 타입 힌트 |
| 10 | +- **필수**: 모든 함수 파라미터와 반환값에 타입 힌트 사용 |
| 11 | +- **형식**: 콜론 앞에 공백 (예: `user_id : str`, `chatbot_id: int`) |
| 12 | + - 일관성은 없지만 대부분 콜론 뒤에만 공백 |
| 13 | +- **타입**: Python 표준 타입 힌트 사용 (`str`, `int`, `dict`, `list` 등) |
| 14 | +- **Optional**: `Optional[T]` 또는 `T | None` 사용 |
| 15 | + |
| 16 | +## 비동기 프로그래밍 |
| 17 | +- **async/await**: FastAPI 엔드포인트와 서비스 로직에서 일관되게 사용 |
| 18 | +- **비동기 함수**: 모든 I/O 작업 (DB, API 호출, gRPC 등)은 비동기로 처리 |
| 19 | +```python |
| 20 | +async def chat(chatbot_id: int, ...) -> BaseResponse: |
| 21 | + chatbot_response = await chatbot_service.chat(...) |
| 22 | + return BaseResponse(...) |
| 23 | +``` |
| 24 | + |
| 25 | +## FastAPI 패턴 |
| 26 | + |
| 27 | +### 라우터 |
| 28 | +- **APIRouter 사용**: 각 도메인별로 라우터 분리 |
| 29 | +- **prefix와 tags**: 라우터 그룹화 |
| 30 | +```python |
| 31 | +router = APIRouter(prefix="/chatbots", tags=["chatbot"]) |
| 32 | +``` |
| 33 | + |
| 34 | +### 의존성 주입 |
| 35 | +- **Depends**: FastAPI의 의존성 주입 시스템 활용 |
| 36 | +```python |
| 37 | +async def chat( |
| 38 | + chatbot_id: int, |
| 39 | + user_id: str = Depends(get_user_id), |
| 40 | + user_grpc_client: UserGrpcClient = Depends(user_stub_dep), |
| 41 | +): |
| 42 | + ... |
| 43 | +``` |
| 44 | + |
| 45 | +### 응답 형식 |
| 46 | +- **BaseResponse**: 일관된 응답 래퍼 사용 |
| 47 | +```python |
| 48 | +return BaseResponse(message="success message", data=response_data) |
| 49 | +``` |
| 50 | + |
| 51 | +## 예외 처리 |
| 52 | +- **BusinessException**: 비즈니스 로직 예외는 커스텀 예외 사용 |
| 53 | +```python |
| 54 | +class BusinessException(Exception): |
| 55 | + def __init__(self, message: str = "에러 발생", status_code: int = 500): |
| 56 | + self.status_code = status_code |
| 57 | + self.message = message |
| 58 | +``` |
| 59 | +- **Global Exception Handler**: `main.py`에서 전역 예외 처리 |
| 60 | + |
| 61 | +## 코멘트 및 문서화 |
| 62 | +- **한글 코멘트**: 코드 내 주석은 한글로 작성 |
| 63 | +```python |
| 64 | +# 캐릭터 챗 |
| 65 | +@router.post("/chat/{chatbot_id}") |
| 66 | +async def chat(...): |
| 67 | + ... |
| 68 | +``` |
| 69 | +- **Docstring**: 복잡한 함수에는 docstring 추가 권장 (하지만 필수는 아님) |
| 70 | + |
| 71 | +## Import 순서 |
| 72 | +1. 표준 라이브러리 |
| 73 | +2. 서드파티 라이브러리 |
| 74 | +3. 로컬 모듈 |
| 75 | + - `core.*` |
| 76 | + - `api.*` |
| 77 | + - `app.*` |
| 78 | + |
| 79 | +예시: |
| 80 | +```python |
| 81 | +from fastapi import APIRouter, Depends, Query |
| 82 | + |
| 83 | +from core.grpcs.client import UserGrpcClient |
| 84 | +from api.depends.get_user_id import get_user_id |
| 85 | +from api.schemas.request.chatbot_request import ChatRequest |
| 86 | +from app.chatbot.service import chatbot_service |
| 87 | +``` |
| 88 | + |
| 89 | +## 파일 구조 |
| 90 | +- **라우터**: `api/routers/` - FastAPI 엔드포인트만 정의 |
| 91 | +- **서비스**: `app/{domain}/service.py` - 비즈니스 로직 |
| 92 | +- **스키마**: `api/schemas/` - Pydantic 모델 |
| 93 | +- **의존성**: `api/depends/`, `core/*/deps/` - 의존성 주입 함수 |
| 94 | + |
| 95 | +## 데이터베이스 |
| 96 | +- **Beanie ORM**: MongoDB 모델 정의 |
| 97 | +- **MongoDB 연결**: 앱 lifespan에서 초기화/종료 |
| 98 | +```python |
| 99 | +@asynccontextmanager |
| 100 | +async def lifespan(app: FastAPI): |
| 101 | + await init_mongodb(app) |
| 102 | + yield |
| 103 | + await close_mongodb(app) |
| 104 | +``` |
| 105 | + |
| 106 | +## 코드 포맷팅 |
| 107 | +- 명시적인 린터/포맷터 설정 파일 없음 |
| 108 | +- 일반적인 Python 컨벤션 따름 (PEP 8 기반) |
| 109 | +- 들여쓰기: 4 스페이스 |
0 commit comments