add logs for tracing processing task
This commit is contained in:
1 parent
efddee217a
commit
073777081e
81 files changed
+25300
-24561
No files matched your search
File diff suppressed because it is too large.
Load diff
+1041
-1041
File diff suppressed because it is too large.
Load diff
+1705
-1705
File diff suppressed because it is too large.
Load diff
+500
-500
@@ -1,500 +1,500 @@
|
||||
# ORM 동기식 전환 보고서
|
||||
|
||||
## 개요
|
||||
|
||||
현재 프로젝트는 **SQLAlchemy 2.0+ 비동기 방식**으로 구현되어 있습니다. 이 보고서는 동기식으로 전환할 경우 필요한 코드 수정 사항을 정리합니다.
|
||||
|
||||
---
|
||||
|
||||
## 1. 현재 비동기 구현 현황
|
||||
|
||||
### 1.1 사용 중인 라이브러리
|
||||
- `sqlalchemy[asyncio]>=2.0.45`
|
||||
- `asyncmy>=0.2.10` (MySQL 비동기 드라이버)
|
||||
- `aiomysql>=0.3.2`
|
||||
|
||||
### 1.2 주요 비동기 컴포넌트
|
||||
| 컴포넌트 | 현재 (비동기) | 변경 후 (동기) |
|
||||
|---------|-------------|--------------|
|
||||
| 엔진 | `create_async_engine` | `create_engine` |
|
||||
| 세션 팩토리 | `async_sessionmaker` | `sessionmaker` |
|
||||
| 세션 클래스 | `AsyncSession` | `Session` |
|
||||
| DB 드라이버 | `mysql+asyncmy` | `mysql+pymysql` |
|
||||
|
||||
---
|
||||
|
||||
## 2. 파일별 수정 사항
|
||||
|
||||
### 2.1 pyproject.toml - 의존성 변경
|
||||
|
||||
**파일**: `pyproject.toml`
|
||||
|
||||
```diff
|
||||
dependencies = [
|
||||
"fastapi[standard]>=0.115.8",
|
||||
- "sqlalchemy[asyncio]>=2.0.45",
|
||||
+ "sqlalchemy>=2.0.45",
|
||||
- "asyncmy>=0.2.10",
|
||||
- "aiomysql>=0.3.2",
|
||||
+ "pymysql>=1.1.0",
|
||||
...
|
||||
]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2.2 config.py - 데이터베이스 URL 변경
|
||||
|
||||
**파일**: `config.py` (라인 74-96)
|
||||
|
||||
```diff
|
||||
class DatabaseSettings(BaseSettings):
|
||||
@property
|
||||
def MYSQL_URL(self) -> str:
|
||||
- return f"mysql+asyncmy://{self.MYSQL_USER}:{self.MYSQL_PASSWORD}@{self.MYSQL_HOST}:{self.MYSQL_PORT}/{self.MYSQL_DB}"
|
||||
+ return f"mysql+pymysql://{self.MYSQL_USER}:{self.MYSQL_PASSWORD}@{self.MYSQL_HOST}:{self.MYSQL_PORT}/{self.MYSQL_DB}"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2.3 app/database/session.py - 세션 설정 전면 수정
|
||||
|
||||
**파일**: `app/database/session.py`
|
||||
|
||||
#### 현재 코드 (비동기)
|
||||
```python
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
from typing import AsyncGenerator
|
||||
|
||||
engine = create_async_engine(
|
||||
url=db_settings.MYSQL_URL,
|
||||
echo=False,
|
||||
pool_size=10,
|
||||
max_overflow=10,
|
||||
pool_timeout=5,
|
||||
pool_recycle=3600,
|
||||
pool_pre_ping=True,
|
||||
pool_reset_on_return="rollback",
|
||||
)
|
||||
|
||||
AsyncSessionLocal = async_sessionmaker(
|
||||
bind=engine,
|
||||
class_=AsyncSession,
|
||||
expire_on_commit=False,
|
||||
autoflush=False,
|
||||
)
|
||||
|
||||
async def get_session() -> AsyncGenerator[AsyncSession, None]:
|
||||
async with AsyncSessionLocal() as session:
|
||||
try:
|
||||
yield session
|
||||
except Exception as e:
|
||||
await session.rollback()
|
||||
raise e
|
||||
```
|
||||
|
||||
#### 변경 후 코드 (동기)
|
||||
```python
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
from typing import Generator
|
||||
|
||||
engine = create_engine(
|
||||
url=db_settings.MYSQL_URL,
|
||||
echo=False,
|
||||
pool_size=10,
|
||||
max_overflow=10,
|
||||
pool_timeout=5,
|
||||
pool_recycle=3600,
|
||||
pool_pre_ping=True,
|
||||
pool_reset_on_return="rollback",
|
||||
)
|
||||
|
||||
SessionLocal = sessionmaker(
|
||||
bind=engine,
|
||||
class_=Session,
|
||||
expire_on_commit=False,
|
||||
autoflush=False,
|
||||
)
|
||||
|
||||
def get_session() -> Generator[Session, None, None]:
|
||||
with SessionLocal() as session:
|
||||
try:
|
||||
yield session
|
||||
except Exception as e:
|
||||
session.rollback()
|
||||
raise e
|
||||
```
|
||||
|
||||
#### get_worker_session 함수 변경
|
||||
|
||||
```diff
|
||||
- from contextlib import asynccontextmanager
|
||||
+ from contextlib import contextmanager
|
||||
|
||||
- @asynccontextmanager
|
||||
- async def get_worker_session() -> AsyncGenerator[AsyncSession, None]:
|
||||
- worker_engine = create_async_engine(
|
||||
+ @contextmanager
|
||||
+ def get_worker_session() -> Generator[Session, None, None]:
|
||||
+ worker_engine = create_engine(
|
||||
url=db_settings.MYSQL_URL,
|
||||
poolclass=NullPool,
|
||||
)
|
||||
- session_factory = async_sessionmaker(
|
||||
- bind=worker_engine,
|
||||
- class_=AsyncSession,
|
||||
+ session_factory = sessionmaker(
|
||||
+ bind=worker_engine,
|
||||
+ class_=Session,
|
||||
expire_on_commit=False,
|
||||
autoflush=False,
|
||||
)
|
||||
|
||||
- async with session_factory() as session:
|
||||
+ with session_factory() as session:
|
||||
try:
|
||||
yield session
|
||||
finally:
|
||||
- await session.close()
|
||||
- await worker_engine.dispose()
|
||||
+ session.close()
|
||||
+ worker_engine.dispose()
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2.4 app/*/dependencies.py - 타입 힌트 변경
|
||||
|
||||
**파일**: `app/song/dependencies.py`, `app/lyric/dependencies.py`, `app/video/dependencies.py`
|
||||
|
||||
```diff
|
||||
- from sqlalchemy.ext.asyncio import AsyncSession
|
||||
+ from sqlalchemy.orm import Session
|
||||
|
||||
- SessionDep = Annotated[AsyncSession, Depends(get_session)]
|
||||
+ SessionDep = Annotated[Session, Depends(get_session)]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2.5 라우터 파일들 - async/await 제거
|
||||
|
||||
**영향받는 파일**:
|
||||
- `app/home/api/routers/v1/home.py`
|
||||
- `app/lyric/api/routers/v1/lyric.py`
|
||||
- `app/song/api/routers/v1/song.py`
|
||||
- `app/video/api/routers/v1/video.py`
|
||||
|
||||
#### 예시: lyric.py (라인 70-90)
|
||||
|
||||
```diff
|
||||
- async def get_lyric_by_task_id(
|
||||
+ def get_lyric_by_task_id(
|
||||
task_id: str,
|
||||
- session: AsyncSession = Depends(get_session),
|
||||
+ session: Session = Depends(get_session),
|
||||
):
|
||||
- result = await session.execute(select(Lyric).where(Lyric.task_id == task_id))
|
||||
+ result = session.execute(select(Lyric).where(Lyric.task_id == task_id))
|
||||
lyric = result.scalar_one_or_none()
|
||||
...
|
||||
```
|
||||
|
||||
#### 예시: CRUD 작업 (라인 218-260)
|
||||
|
||||
```diff
|
||||
- async def create_project(
|
||||
+ def create_project(
|
||||
request_body: ProjectCreateRequest,
|
||||
- session: AsyncSession = Depends(get_session),
|
||||
+ session: Session = Depends(get_session),
|
||||
):
|
||||
project = Project(
|
||||
store_name=request_body.customer_name,
|
||||
region=request_body.region,
|
||||
task_id=task_id,
|
||||
)
|
||||
session.add(project)
|
||||
- await session.commit()
|
||||
- await session.refresh(project)
|
||||
+ session.commit()
|
||||
+ session.refresh(project)
|
||||
return project
|
||||
```
|
||||
|
||||
#### 예시: 플러시 작업 (home.py 라인 340-350)
|
||||
|
||||
```diff
|
||||
session.add(image)
|
||||
- await session.flush()
|
||||
+ session.flush()
|
||||
result = image.id
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2.6 서비스 파일들 - Raw SQL 쿼리 변경
|
||||
|
||||
**영향받는 파일**:
|
||||
- `app/lyric/services/lyrics.py`
|
||||
- `app/song/services/song.py`
|
||||
- `app/video/services/video.py`
|
||||
|
||||
#### 예시: lyrics.py (라인 20-30)
|
||||
|
||||
```diff
|
||||
- async def get_store_default_info(conn: AsyncConnection):
|
||||
+ def get_store_default_info(conn: Connection):
|
||||
query = """SELECT * FROM store_default_info;"""
|
||||
- result = await conn.execute(text(query))
|
||||
+ result = conn.execute(text(query))
|
||||
return result.fetchall()
|
||||
```
|
||||
|
||||
#### 예시: INSERT 쿼리 (라인 360-400)
|
||||
|
||||
```diff
|
||||
- async def insert_song_result(conn: AsyncConnection, params: dict):
|
||||
+ def insert_song_result(conn: Connection, params: dict):
|
||||
insert_query = """INSERT INTO song_results_all (...) VALUES (...)"""
|
||||
- await conn.execute(text(insert_query), params)
|
||||
- await conn.commit()
|
||||
+ conn.execute(text(insert_query), params)
|
||||
+ conn.commit()
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2.7 app/home/services/base.py - BaseService 클래스
|
||||
|
||||
**파일**: `app/home/services/base.py`
|
||||
|
||||
```diff
|
||||
- from sqlalchemy.ext.asyncio import AsyncSession
|
||||
+ from sqlalchemy.orm import Session
|
||||
|
||||
class BaseService:
|
||||
- def __init__(self, model, session: AsyncSession):
|
||||
+ def __init__(self, model, session: Session):
|
||||
self.model = model
|
||||
self.session = session
|
||||
|
||||
- async def _get(self, id: UUID):
|
||||
- return await self.session.get(self.model, id)
|
||||
+ def _get(self, id: UUID):
|
||||
+ return self.session.get(self.model, id)
|
||||
|
||||
- async def _add(self, entity):
|
||||
+ def _add(self, entity):
|
||||
self.session.add(entity)
|
||||
- await self.session.commit()
|
||||
- await self.session.refresh(entity)
|
||||
+ self.session.commit()
|
||||
+ self.session.refresh(entity)
|
||||
return entity
|
||||
|
||||
- async def _update(self, entity):
|
||||
- return await self._add(entity)
|
||||
+ def _update(self, entity):
|
||||
+ return self._add(entity)
|
||||
|
||||
- async def _delete(self, entity):
|
||||
- await self.session.delete(entity)
|
||||
+ def _delete(self, entity):
|
||||
+ self.session.delete(entity)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 모델 파일 - 변경 불필요
|
||||
|
||||
다음 모델 파일들은 **변경이 필요 없습니다**:
|
||||
- `app/home/models.py`
|
||||
- `app/lyric/models.py`
|
||||
- `app/song/models.py`
|
||||
- `app/video/models.py`
|
||||
|
||||
모델 정의 자체는 비동기/동기와 무관하게 동일합니다. `Mapped`, `mapped_column`, `relationship` 등은 그대로 사용 가능합니다.
|
||||
|
||||
단, **관계 로딩 전략**에서 `lazy="selectin"` 설정은 동기 환경에서도 작동하지만, 필요에 따라 `lazy="joined"` 또는 `lazy="subquery"`로 변경할 수 있습니다.
|
||||
|
||||
---
|
||||
|
||||
## 4. 수정 패턴 요약
|
||||
|
||||
### 4.1 Import 변경 패턴
|
||||
|
||||
```diff
|
||||
# 엔진/세션 관련
|
||||
- from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
+ from sqlalchemy import create_engine
|
||||
+ from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
# 타입 힌트
|
||||
- from typing import AsyncGenerator
|
||||
+ from typing import Generator
|
||||
|
||||
# 컨텍스트 매니저
|
||||
- from contextlib import asynccontextmanager
|
||||
+ from contextlib import contextmanager
|
||||
```
|
||||
|
||||
### 4.2 함수 정의 변경 패턴
|
||||
|
||||
```diff
|
||||
- async def function_name(...):
|
||||
+ def function_name(...):
|
||||
```
|
||||
|
||||
### 4.3 await 제거 패턴
|
||||
|
||||
```diff
|
||||
- result = await session.execute(query)
|
||||
+ result = session.execute(query)
|
||||
|
||||
- await session.commit()
|
||||
+ session.commit()
|
||||
|
||||
- await session.refresh(obj)
|
||||
+ session.refresh(obj)
|
||||
|
||||
- await session.flush()
|
||||
+ session.flush()
|
||||
|
||||
- await session.rollback()
|
||||
+ session.rollback()
|
||||
|
||||
- await session.close()
|
||||
+ session.close()
|
||||
|
||||
- await engine.dispose()
|
||||
+ engine.dispose()
|
||||
```
|
||||
|
||||
### 4.4 컨텍스트 매니저 변경 패턴
|
||||
|
||||
```diff
|
||||
- async with SessionLocal() as session:
|
||||
+ with SessionLocal() as session:
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. 영향받는 파일 목록
|
||||
|
||||
### 5.1 반드시 수정해야 하는 파일
|
||||
|
||||
| 파일 | 수정 범위 |
|
||||
|-----|---------|
|
||||
| `pyproject.toml` | 의존성 변경 |
|
||||
| `config.py` | DB URL 변경 |
|
||||
| `app/database/session.py` | 전면 수정 |
|
||||
| `app/database/session-prod.py` | 전면 수정 |
|
||||
| `app/home/api/routers/v1/home.py` | async/await 제거 |
|
||||
| `app/lyric/api/routers/v1/lyric.py` | async/await 제거 |
|
||||
| `app/song/api/routers/v1/song.py` | async/await 제거 |
|
||||
| `app/video/api/routers/v1/video.py` | async/await 제거 |
|
||||
| `app/lyric/services/lyrics.py` | async/await 제거 |
|
||||
| `app/song/services/song.py` | async/await 제거 |
|
||||
| `app/video/services/video.py` | async/await 제거 |
|
||||
| `app/home/services/base.py` | async/await 제거 |
|
||||
| `app/song/dependencies.py` | 타입 힌트 변경 |
|
||||
| `app/lyric/dependencies.py` | 타입 힌트 변경 |
|
||||
| `app/video/dependencies.py` | 타입 힌트 변경 |
|
||||
| `app/dependencies/database.py` | 타입 힌트 변경 |
|
||||
|
||||
### 5.2 수정 불필요한 파일
|
||||
|
||||
| 파일 | 이유 |
|
||||
|-----|-----|
|
||||
| `app/home/models.py` | 모델 정의는 동기/비동기 무관 |
|
||||
| `app/lyric/models.py` | 모델 정의는 동기/비동기 무관 |
|
||||
| `app/song/models.py` | 모델 정의는 동기/비동기 무관 |
|
||||
| `app/video/models.py` | 모델 정의는 동기/비동기 무관 |
|
||||
|
||||
---
|
||||
|
||||
## 6. 주의사항
|
||||
|
||||
### 6.1 FastAPI와의 호환성
|
||||
|
||||
FastAPI는 동기 엔드포인트도 지원합니다. 동기 함수는 스레드 풀에서 실행됩니다:
|
||||
|
||||
```python
|
||||
# 동기 엔드포인트 - FastAPI가 자동으로 스레드풀에서 실행
|
||||
@router.get("/items/{item_id}")
|
||||
def get_item(item_id: int, session: Session = Depends(get_session)):
|
||||
return session.get(Item, item_id)
|
||||
```
|
||||
|
||||
### 6.2 성능 고려사항
|
||||
|
||||
동기식으로 전환 시 고려할 점:
|
||||
- **동시성 감소**: 비동기 I/O의 이점 상실
|
||||
- **스레드 풀 의존**: 동시 요청이 많을 경우 스레드 풀 크기 조정 필요
|
||||
- **블로킹 I/O**: DB 쿼리 중 다른 요청 처리 불가
|
||||
|
||||
### 6.3 백그라운드 작업
|
||||
|
||||
현재 `get_worker_session()`으로 별도 이벤트 루프에서 실행되는 백그라운드 작업이 있습니다. 동기식 전환 시 스레드 기반 백그라운드 작업으로 변경해야 합니다:
|
||||
|
||||
```python
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
executor = ThreadPoolExecutor(max_workers=4)
|
||||
|
||||
def background_task():
|
||||
with get_worker_session() as session:
|
||||
# 작업 수행
|
||||
pass
|
||||
|
||||
# 실행
|
||||
executor.submit(background_task)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. 마이그레이션 단계
|
||||
|
||||
### Step 1: 의존성 변경
|
||||
1. `pyproject.toml` 수정
|
||||
2. `pip install pymysql` 또는 `uv sync` 실행
|
||||
|
||||
### Step 2: 설정 파일 수정
|
||||
1. `config.py`의 DB URL 변경
|
||||
2. `app/database/session.py` 전면 수정
|
||||
|
||||
### Step 3: 라우터 수정
|
||||
1. 각 라우터 파일의 `async def` → `def` 변경
|
||||
2. 모든 `await` 키워드 제거
|
||||
3. `AsyncSession` → `Session` 타입 힌트 변경
|
||||
|
||||
### Step 4: 서비스 수정
|
||||
1. 서비스 파일들의 async/await 제거
|
||||
2. Raw SQL 쿼리 함수들 수정
|
||||
|
||||
### Step 5: 의존성 수정
|
||||
1. `dependencies.py` 파일들의 타입 힌트 변경
|
||||
|
||||
### Step 6: 테스트
|
||||
1. 모든 엔드포인트 기능 테스트
|
||||
2. 성능 테스트 (동시 요청 처리 확인)
|
||||
|
||||
---
|
||||
|
||||
## 8. 결론
|
||||
|
||||
비동기에서 동기로 전환은 기술적으로 가능하지만, 다음을 고려해야 합니다:
|
||||
|
||||
**장점**:
|
||||
- 코드 복잡도 감소 (async/await 제거)
|
||||
- 디버깅 용이
|
||||
- 레거시 라이브러리와의 호환성 향상
|
||||
|
||||
**단점**:
|
||||
- 동시성 처리 능력 감소
|
||||
- I/O 바운드 작업에서 성능 저하 가능
|
||||
- FastAPI의 비동기 장점 미활용
|
||||
|
||||
현재 프로젝트가 FastAPI 기반이고 I/O 작업(DB, 외부 API 호출)이 많다면, **비동기 유지를 권장**합니다. 동기 전환은 특별한 요구사항(레거시 통합, 팀 역량 등)이 있을 때만 고려하시기 바랍니다.
|
||||
# ORM 동기식 전환 보고서
|
||||
|
||||
## 개요
|
||||
|
||||
현재 프로젝트는 **SQLAlchemy 2.0+ 비동기 방식**으로 구현되어 있습니다. 이 보고서는 동기식으로 전환할 경우 필요한 코드 수정 사항을 정리합니다.
|
||||
|
||||
---
|
||||
|
||||
## 1. 현재 비동기 구현 현황
|
||||
|
||||
### 1.1 사용 중인 라이브러리
|
||||
- `sqlalchemy[asyncio]>=2.0.45`
|
||||
- `asyncmy>=0.2.10` (MySQL 비동기 드라이버)
|
||||
- `aiomysql>=0.3.2`
|
||||
|
||||
### 1.2 주요 비동기 컴포넌트
|
||||
| 컴포넌트 | 현재 (비동기) | 변경 후 (동기) |
|
||||
|---------|-------------|--------------|
|
||||
| 엔진 | `create_async_engine` | `create_engine` |
|
||||
| 세션 팩토리 | `async_sessionmaker` | `sessionmaker` |
|
||||
| 세션 클래스 | `AsyncSession` | `Session` |
|
||||
| DB 드라이버 | `mysql+asyncmy` | `mysql+pymysql` |
|
||||
|
||||
---
|
||||
|
||||
## 2. 파일별 수정 사항
|
||||
|
||||
### 2.1 pyproject.toml - 의존성 변경
|
||||
|
||||
**파일**: `pyproject.toml`
|
||||
|
||||
```diff
|
||||
dependencies = [
|
||||
"fastapi[standard]>=0.115.8",
|
||||
- "sqlalchemy[asyncio]>=2.0.45",
|
||||
+ "sqlalchemy>=2.0.45",
|
||||
- "asyncmy>=0.2.10",
|
||||
- "aiomysql>=0.3.2",
|
||||
+ "pymysql>=1.1.0",
|
||||
...
|
||||
]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2.2 config.py - 데이터베이스 URL 변경
|
||||
|
||||
**파일**: `config.py` (라인 74-96)
|
||||
|
||||
```diff
|
||||
class DatabaseSettings(BaseSettings):
|
||||
@property
|
||||
def MYSQL_URL(self) -> str:
|
||||
- return f"mysql+asyncmy://{self.MYSQL_USER}:{self.MYSQL_PASSWORD}@{self.MYSQL_HOST}:{self.MYSQL_PORT}/{self.MYSQL_DB}"
|
||||
+ return f"mysql+pymysql://{self.MYSQL_USER}:{self.MYSQL_PASSWORD}@{self.MYSQL_HOST}:{self.MYSQL_PORT}/{self.MYSQL_DB}"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2.3 app/database/session.py - 세션 설정 전면 수정
|
||||
|
||||
**파일**: `app/database/session.py`
|
||||
|
||||
#### 현재 코드 (비동기)
|
||||
```python
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
from typing import AsyncGenerator
|
||||
|
||||
engine = create_async_engine(
|
||||
url=db_settings.MYSQL_URL,
|
||||
echo=False,
|
||||
pool_size=10,
|
||||
max_overflow=10,
|
||||
pool_timeout=5,
|
||||
pool_recycle=3600,
|
||||
pool_pre_ping=True,
|
||||
pool_reset_on_return="rollback",
|
||||
)
|
||||
|
||||
AsyncSessionLocal = async_sessionmaker(
|
||||
bind=engine,
|
||||
class_=AsyncSession,
|
||||
expire_on_commit=False,
|
||||
autoflush=False,
|
||||
)
|
||||
|
||||
async def get_session() -> AsyncGenerator[AsyncSession, None]:
|
||||
async with AsyncSessionLocal() as session:
|
||||
try:
|
||||
yield session
|
||||
except Exception as e:
|
||||
await session.rollback()
|
||||
raise e
|
||||
```
|
||||
|
||||
#### 변경 후 코드 (동기)
|
||||
```python
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
from typing import Generator
|
||||
|
||||
engine = create_engine(
|
||||
url=db_settings.MYSQL_URL,
|
||||
echo=False,
|
||||
pool_size=10,
|
||||
max_overflow=10,
|
||||
pool_timeout=5,
|
||||
pool_recycle=3600,
|
||||
pool_pre_ping=True,
|
||||
pool_reset_on_return="rollback",
|
||||
)
|
||||
|
||||
SessionLocal = sessionmaker(
|
||||
bind=engine,
|
||||
class_=Session,
|
||||
expire_on_commit=False,
|
||||
autoflush=False,
|
||||
)
|
||||
|
||||
def get_session() -> Generator[Session, None, None]:
|
||||
with SessionLocal() as session:
|
||||
try:
|
||||
yield session
|
||||
except Exception as e:
|
||||
session.rollback()
|
||||
raise e
|
||||
```
|
||||
|
||||
#### get_worker_session 함수 변경
|
||||
|
||||
```diff
|
||||
- from contextlib import asynccontextmanager
|
||||
+ from contextlib import contextmanager
|
||||
|
||||
- @asynccontextmanager
|
||||
- async def get_worker_session() -> AsyncGenerator[AsyncSession, None]:
|
||||
- worker_engine = create_async_engine(
|
||||
+ @contextmanager
|
||||
+ def get_worker_session() -> Generator[Session, None, None]:
|
||||
+ worker_engine = create_engine(
|
||||
url=db_settings.MYSQL_URL,
|
||||
poolclass=NullPool,
|
||||
)
|
||||
- session_factory = async_sessionmaker(
|
||||
- bind=worker_engine,
|
||||
- class_=AsyncSession,
|
||||
+ session_factory = sessionmaker(
|
||||
+ bind=worker_engine,
|
||||
+ class_=Session,
|
||||
expire_on_commit=False,
|
||||
autoflush=False,
|
||||
)
|
||||
|
||||
- async with session_factory() as session:
|
||||
+ with session_factory() as session:
|
||||
try:
|
||||
yield session
|
||||
finally:
|
||||
- await session.close()
|
||||
- await worker_engine.dispose()
|
||||
+ session.close()
|
||||
+ worker_engine.dispose()
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2.4 app/*/dependencies.py - 타입 힌트 변경
|
||||
|
||||
**파일**: `app/song/dependencies.py`, `app/lyric/dependencies.py`, `app/video/dependencies.py`
|
||||
|
||||
```diff
|
||||
- from sqlalchemy.ext.asyncio import AsyncSession
|
||||
+ from sqlalchemy.orm import Session
|
||||
|
||||
- SessionDep = Annotated[AsyncSession, Depends(get_session)]
|
||||
+ SessionDep = Annotated[Session, Depends(get_session)]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2.5 라우터 파일들 - async/await 제거
|
||||
|
||||
**영향받는 파일**:
|
||||
- `app/home/api/routers/v1/home.py`
|
||||
- `app/lyric/api/routers/v1/lyric.py`
|
||||
- `app/song/api/routers/v1/song.py`
|
||||
- `app/video/api/routers/v1/video.py`
|
||||
|
||||
#### 예시: lyric.py (라인 70-90)
|
||||
|
||||
```diff
|
||||
- async def get_lyric_by_task_id(
|
||||
+ def get_lyric_by_task_id(
|
||||
task_id: str,
|
||||
- session: AsyncSession = Depends(get_session),
|
||||
+ session: Session = Depends(get_session),
|
||||
):
|
||||
- result = await session.execute(select(Lyric).where(Lyric.task_id == task_id))
|
||||
+ result = session.execute(select(Lyric).where(Lyric.task_id == task_id))
|
||||
lyric = result.scalar_one_or_none()
|
||||
...
|
||||
```
|
||||
|
||||
#### 예시: CRUD 작업 (라인 218-260)
|
||||
|
||||
```diff
|
||||
- async def create_project(
|
||||
+ def create_project(
|
||||
request_body: ProjectCreateRequest,
|
||||
- session: AsyncSession = Depends(get_session),
|
||||
+ session: Session = Depends(get_session),
|
||||
):
|
||||
project = Project(
|
||||
store_name=request_body.customer_name,
|
||||
region=request_body.region,
|
||||
task_id=task_id,
|
||||
)
|
||||
session.add(project)
|
||||
- await session.commit()
|
||||
- await session.refresh(project)
|
||||
+ session.commit()
|
||||
+ session.refresh(project)
|
||||
return project
|
||||
```
|
||||
|
||||
#### 예시: 플러시 작업 (home.py 라인 340-350)
|
||||
|
||||
```diff
|
||||
session.add(image)
|
||||
- await session.flush()
|
||||
+ session.flush()
|
||||
result = image.id
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2.6 서비스 파일들 - Raw SQL 쿼리 변경
|
||||
|
||||
**영향받는 파일**:
|
||||
- `app/lyric/services/lyrics.py`
|
||||
- `app/song/services/song.py`
|
||||
- `app/video/services/video.py`
|
||||
|
||||
#### 예시: lyrics.py (라인 20-30)
|
||||
|
||||
```diff
|
||||
- async def get_store_default_info(conn: AsyncConnection):
|
||||
+ def get_store_default_info(conn: Connection):
|
||||
query = """SELECT * FROM store_default_info;"""
|
||||
- result = await conn.execute(text(query))
|
||||
+ result = conn.execute(text(query))
|
||||
return result.fetchall()
|
||||
```
|
||||
|
||||
#### 예시: INSERT 쿼리 (라인 360-400)
|
||||
|
||||
```diff
|
||||
- async def insert_song_result(conn: AsyncConnection, params: dict):
|
||||
+ def insert_song_result(conn: Connection, params: dict):
|
||||
insert_query = """INSERT INTO song_results_all (...) VALUES (...)"""
|
||||
- await conn.execute(text(insert_query), params)
|
||||
- await conn.commit()
|
||||
+ conn.execute(text(insert_query), params)
|
||||
+ conn.commit()
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2.7 app/home/services/base.py - BaseService 클래스
|
||||
|
||||
**파일**: `app/home/services/base.py`
|
||||
|
||||
```diff
|
||||
- from sqlalchemy.ext.asyncio import AsyncSession
|
||||
+ from sqlalchemy.orm import Session
|
||||
|
||||
class BaseService:
|
||||
- def __init__(self, model, session: AsyncSession):
|
||||
+ def __init__(self, model, session: Session):
|
||||
self.model = model
|
||||
self.session = session
|
||||
|
||||
- async def _get(self, id: UUID):
|
||||
- return await self.session.get(self.model, id)
|
||||
+ def _get(self, id: UUID):
|
||||
+ return self.session.get(self.model, id)
|
||||
|
||||
- async def _add(self, entity):
|
||||
+ def _add(self, entity):
|
||||
self.session.add(entity)
|
||||
- await self.session.commit()
|
||||
- await self.session.refresh(entity)
|
||||
+ self.session.commit()
|
||||
+ self.session.refresh(entity)
|
||||
return entity
|
||||
|
||||
- async def _update(self, entity):
|
||||
- return await self._add(entity)
|
||||
+ def _update(self, entity):
|
||||
+ return self._add(entity)
|
||||
|
||||
- async def _delete(self, entity):
|
||||
- await self.session.delete(entity)
|
||||
+ def _delete(self, entity):
|
||||
+ self.session.delete(entity)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 모델 파일 - 변경 불필요
|
||||
|
||||
다음 모델 파일들은 **변경이 필요 없습니다**:
|
||||
- `app/home/models.py`
|
||||
- `app/lyric/models.py`
|
||||
- `app/song/models.py`
|
||||
- `app/video/models.py`
|
||||
|
||||
모델 정의 자체는 비동기/동기와 무관하게 동일합니다. `Mapped`, `mapped_column`, `relationship` 등은 그대로 사용 가능합니다.
|
||||
|
||||
단, **관계 로딩 전략**에서 `lazy="selectin"` 설정은 동기 환경에서도 작동하지만, 필요에 따라 `lazy="joined"` 또는 `lazy="subquery"`로 변경할 수 있습니다.
|
||||
|
||||
---
|
||||
|
||||
## 4. 수정 패턴 요약
|
||||
|
||||
### 4.1 Import 변경 패턴
|
||||
|
||||
```diff
|
||||
# 엔진/세션 관련
|
||||
- from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
+ from sqlalchemy import create_engine
|
||||
+ from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
# 타입 힌트
|
||||
- from typing import AsyncGenerator
|
||||
+ from typing import Generator
|
||||
|
||||
# 컨텍스트 매니저
|
||||
- from contextlib import asynccontextmanager
|
||||
+ from contextlib import contextmanager
|
||||
```
|
||||
|
||||
### 4.2 함수 정의 변경 패턴
|
||||
|
||||
```diff
|
||||
- async def function_name(...):
|
||||
+ def function_name(...):
|
||||
```
|
||||
|
||||
### 4.3 await 제거 패턴
|
||||
|
||||
```diff
|
||||
- result = await session.execute(query)
|
||||
+ result = session.execute(query)
|
||||
|
||||
- await session.commit()
|
||||
+ session.commit()
|
||||
|
||||
- await session.refresh(obj)
|
||||
+ session.refresh(obj)
|
||||
|
||||
- await session.flush()
|
||||
+ session.flush()
|
||||
|
||||
- await session.rollback()
|
||||
+ session.rollback()
|
||||
|
||||
- await session.close()
|
||||
+ session.close()
|
||||
|
||||
- await engine.dispose()
|
||||
+ engine.dispose()
|
||||
```
|
||||
|
||||
### 4.4 컨텍스트 매니저 변경 패턴
|
||||
|
||||
```diff
|
||||
- async with SessionLocal() as session:
|
||||
+ with SessionLocal() as session:
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. 영향받는 파일 목록
|
||||
|
||||
### 5.1 반드시 수정해야 하는 파일
|
||||
|
||||
| 파일 | 수정 범위 |
|
||||
|-----|---------|
|
||||
| `pyproject.toml` | 의존성 변경 |
|
||||
| `config.py` | DB URL 변경 |
|
||||
| `app/database/session.py` | 전면 수정 |
|
||||
| `app/database/session-prod.py` | 전면 수정 |
|
||||
| `app/home/api/routers/v1/home.py` | async/await 제거 |
|
||||
| `app/lyric/api/routers/v1/lyric.py` | async/await 제거 |
|
||||
| `app/song/api/routers/v1/song.py` | async/await 제거 |
|
||||
| `app/video/api/routers/v1/video.py` | async/await 제거 |
|
||||
| `app/lyric/services/lyrics.py` | async/await 제거 |
|
||||
| `app/song/services/song.py` | async/await 제거 |
|
||||
| `app/video/services/video.py` | async/await 제거 |
|
||||
| `app/home/services/base.py` | async/await 제거 |
|
||||
| `app/song/dependencies.py` | 타입 힌트 변경 |
|
||||
| `app/lyric/dependencies.py` | 타입 힌트 변경 |
|
||||
| `app/video/dependencies.py` | 타입 힌트 변경 |
|
||||
| `app/dependencies/database.py` | 타입 힌트 변경 |
|
||||
|
||||
### 5.2 수정 불필요한 파일
|
||||
|
||||
| 파일 | 이유 |
|
||||
|-----|-----|
|
||||
| `app/home/models.py` | 모델 정의는 동기/비동기 무관 |
|
||||
| `app/lyric/models.py` | 모델 정의는 동기/비동기 무관 |
|
||||
| `app/song/models.py` | 모델 정의는 동기/비동기 무관 |
|
||||
| `app/video/models.py` | 모델 정의는 동기/비동기 무관 |
|
||||
|
||||
---
|
||||
|
||||
## 6. 주의사항
|
||||
|
||||
### 6.1 FastAPI와의 호환성
|
||||
|
||||
FastAPI는 동기 엔드포인트도 지원합니다. 동기 함수는 스레드 풀에서 실행됩니다:
|
||||
|
||||
```python
|
||||
# 동기 엔드포인트 - FastAPI가 자동으로 스레드풀에서 실행
|
||||
@router.get("/items/{item_id}")
|
||||
def get_item(item_id: int, session: Session = Depends(get_session)):
|
||||
return session.get(Item, item_id)
|
||||
```
|
||||
|
||||
### 6.2 성능 고려사항
|
||||
|
||||
동기식으로 전환 시 고려할 점:
|
||||
- **동시성 감소**: 비동기 I/O의 이점 상실
|
||||
- **스레드 풀 의존**: 동시 요청이 많을 경우 스레드 풀 크기 조정 필요
|
||||
- **블로킹 I/O**: DB 쿼리 중 다른 요청 처리 불가
|
||||
|
||||
### 6.3 백그라운드 작업
|
||||
|
||||
현재 `get_worker_session()`으로 별도 이벤트 루프에서 실행되는 백그라운드 작업이 있습니다. 동기식 전환 시 스레드 기반 백그라운드 작업으로 변경해야 합니다:
|
||||
|
||||
```python
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
executor = ThreadPoolExecutor(max_workers=4)
|
||||
|
||||
def background_task():
|
||||
with get_worker_session() as session:
|
||||
# 작업 수행
|
||||
pass
|
||||
|
||||
# 실행
|
||||
executor.submit(background_task)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. 마이그레이션 단계
|
||||
|
||||
### Step 1: 의존성 변경
|
||||
1. `pyproject.toml` 수정
|
||||
2. `pip install pymysql` 또는 `uv sync` 실행
|
||||
|
||||
### Step 2: 설정 파일 수정
|
||||
1. `config.py`의 DB URL 변경
|
||||
2. `app/database/session.py` 전면 수정
|
||||
|
||||
### Step 3: 라우터 수정
|
||||
1. 각 라우터 파일의 `async def` → `def` 변경
|
||||
2. 모든 `await` 키워드 제거
|
||||
3. `AsyncSession` → `Session` 타입 힌트 변경
|
||||
|
||||
### Step 4: 서비스 수정
|
||||
1. 서비스 파일들의 async/await 제거
|
||||
2. Raw SQL 쿼리 함수들 수정
|
||||
|
||||
### Step 5: 의존성 수정
|
||||
1. `dependencies.py` 파일들의 타입 힌트 변경
|
||||
|
||||
### Step 6: 테스트
|
||||
1. 모든 엔드포인트 기능 테스트
|
||||
2. 성능 테스트 (동시 요청 처리 확인)
|
||||
|
||||
---
|
||||
|
||||
## 8. 결론
|
||||
|
||||
비동기에서 동기로 전환은 기술적으로 가능하지만, 다음을 고려해야 합니다:
|
||||
|
||||
**장점**:
|
||||
- 코드 복잡도 감소 (async/await 제거)
|
||||
- 디버깅 용이
|
||||
- 레거시 라이브러리와의 호환성 향상
|
||||
|
||||
**단점**:
|
||||
- 동시성 처리 능력 감소
|
||||
- I/O 바운드 작업에서 성능 저하 가능
|
||||
- FastAPI의 비동기 장점 미활용
|
||||
|
||||
현재 프로젝트가 FastAPI 기반이고 I/O 작업(DB, 외부 API 호출)이 많다면, **비동기 유지를 권장**합니다. 동기 전환은 특별한 요구사항(레거시 통합, 팀 역량 등)이 있을 때만 고려하시기 바랍니다.
|
||||
+297
-297
@@ -1,297 +1,297 @@
|
||||
# 비동기 처리 문제 분석 보고서
|
||||
|
||||
## 요약
|
||||
|
||||
전반적으로 이 프로젝트는 현대적인 비동기 아키텍처를 잘 구현하고 있습니다. 그러나 몇 가지 잠재적인 문제점과 개선 가능한 부분이 발견되었습니다.
|
||||
|
||||
---
|
||||
|
||||
## 1. 심각도 높음 - 즉시 개선 권장
|
||||
|
||||
### 1.1 N+1 쿼리 문제 (video.py:596-612)
|
||||
|
||||
```python
|
||||
# get_videos() 엔드포인트에서
|
||||
for video in videos:
|
||||
# 매 video마다 별도의 DB 쿼리 실행 - N+1 문제!
|
||||
project_result = await session.execute(
|
||||
select(Project).where(Project.id == video.project_id)
|
||||
)
|
||||
project = project_result.scalar_one_or_none()
|
||||
```
|
||||
|
||||
**문제점**: 비디오 목록 조회 시 각 비디오마다 별도의 Project 쿼리가 발생합니다. 10개 비디오 조회 시 11번의 DB 쿼리가 실행됩니다.
|
||||
|
||||
**개선 방안**:
|
||||
```python
|
||||
# selectinload를 사용한 eager loading
|
||||
from sqlalchemy.orm import selectinload
|
||||
|
||||
query = (
|
||||
select(Video)
|
||||
.options(selectinload(Video.project)) # relationship 필요
|
||||
.where(Video.id.in_(select(subquery.c.max_id)))
|
||||
.order_by(Video.created_at.desc())
|
||||
.offset(offset)
|
||||
.limit(pagination.page_size)
|
||||
)
|
||||
|
||||
# 또는 한 번에 project_ids 수집 후 일괄 조회
|
||||
project_ids = [v.project_id for v in videos]
|
||||
projects_result = await session.execute(
|
||||
select(Project).where(Project.id.in_(project_ids))
|
||||
)
|
||||
projects_map = {p.id: p for p in projects_result.scalars().all()}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 1.2 가사 생성 API의 블로킹 문제 (lyric.py:274-276)
|
||||
|
||||
```python
|
||||
# ChatGPT API 호출이 완료될 때까지 HTTP 응답이 블로킹됨
|
||||
print(f"[generate_lyric] ChatGPT generation started - task_id: {task_id}")
|
||||
result = await service.generate(prompt=prompt) # 수 초~수십 초 소요
|
||||
print(f"[generate_lyric] ChatGPT generation completed - task_id: {task_id}")
|
||||
```
|
||||
|
||||
**문제점**:
|
||||
- ChatGPT API 응답이 5-30초 이상 걸릴 수 있음
|
||||
- 이 시간 동안 클라이언트 연결이 유지되어야 함
|
||||
- 다수 동시 요청 시 worker 스레드 고갈 가능성
|
||||
|
||||
**개선 방안 (BackgroundTask 패턴)**:
|
||||
```python
|
||||
@router.post("/generate")
|
||||
async def generate_lyric(
|
||||
request_body: GenerateLyricRequest,
|
||||
background_tasks: BackgroundTasks,
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> GenerateLyricResponse:
|
||||
# DB에 processing 상태로 저장
|
||||
lyric = Lyric(status="processing", ...)
|
||||
session.add(lyric)
|
||||
await session.commit()
|
||||
|
||||
# 백그라운드에서 ChatGPT 호출
|
||||
background_tasks.add_task(
|
||||
generate_lyric_background,
|
||||
task_id=task_id,
|
||||
prompt=prompt,
|
||||
)
|
||||
|
||||
# 즉시 응답 반환
|
||||
return GenerateLyricResponse(
|
||||
success=True,
|
||||
task_id=task_id,
|
||||
message="가사 생성이 시작되었습니다. /status/{task_id}로 상태를 확인하세요.",
|
||||
)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 1.3 Creatomate 서비스의 동기/비동기 메서드 혼재 (creatomate.py)
|
||||
|
||||
**문제점**: 동기 메서드가 여전히 존재하여 실수로 async 컨텍스트에서 호출될 수 있습니다.
|
||||
|
||||
| 동기 메서드 | 비동기 메서드 |
|
||||
|------------|--------------|
|
||||
| `get_all_templates_data()` | 없음 |
|
||||
| `get_one_template_data()` | `get_one_template_data_async()` |
|
||||
| `make_creatomate_call()` | 없음 |
|
||||
| `make_creatomate_custom_call()` | `make_creatomate_custom_call_async()` |
|
||||
| `get_render_status()` | `get_render_status_async()` |
|
||||
|
||||
**개선 방안**:
|
||||
```python
|
||||
# 모든 HTTP 호출 메서드를 async로 통일
|
||||
async def get_all_templates_data(self) -> dict:
|
||||
url = f"{self.BASE_URL}/v1/templates"
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.get(url, headers=self.headers, timeout=30.0)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
# 동기 버전 제거 또는 deprecated 표시
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. 심각도 중간 - 개선 권장
|
||||
|
||||
### 2.1 백그라운드 태스크에서 매번 엔진 생성 (session.py:82-127)
|
||||
|
||||
```python
|
||||
@asynccontextmanager
|
||||
async def get_worker_session() -> AsyncGenerator[AsyncSession, None]:
|
||||
# 매 호출마다 새 엔진 생성 - 오버헤드 발생
|
||||
worker_engine = create_async_engine(
|
||||
url=db_settings.MYSQL_URL,
|
||||
poolclass=NullPool,
|
||||
...
|
||||
)
|
||||
```
|
||||
|
||||
**문제점**: 백그라운드 태스크가 빈번하게 호출되면 엔진 생성/소멸 오버헤드가 증가합니다.
|
||||
|
||||
**개선 방안**:
|
||||
```python
|
||||
# 모듈 레벨에서 워커 전용 엔진 생성
|
||||
_worker_engine = create_async_engine(
|
||||
url=db_settings.MYSQL_URL,
|
||||
poolclass=NullPool,
|
||||
)
|
||||
_WorkerSessionLocal = async_sessionmaker(bind=_worker_engine, ...)
|
||||
|
||||
@asynccontextmanager
|
||||
async def get_worker_session() -> AsyncGenerator[AsyncSession, None]:
|
||||
async with _WorkerSessionLocal() as session:
|
||||
try:
|
||||
yield session
|
||||
except Exception as e:
|
||||
await session.rollback()
|
||||
raise e
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2.2 대용량 파일 다운로드 시 메모리 사용 (video_task.py:49-54)
|
||||
|
||||
```python
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.get(video_url, timeout=180.0)
|
||||
response.raise_for_status()
|
||||
# 전체 파일을 메모리에 로드 - 대용량 영상 시 문제
|
||||
async with aiofiles.open(str(temp_file_path), "wb") as f:
|
||||
await f.write(response.content)
|
||||
```
|
||||
|
||||
**문제점**: 수백 MB 크기의 영상 파일을 한 번에 메모리에 로드합니다.
|
||||
|
||||
**개선 방안 - 스트리밍 다운로드**:
|
||||
```python
|
||||
async with httpx.AsyncClient() as client:
|
||||
async with client.stream("GET", video_url, timeout=180.0) as response:
|
||||
response.raise_for_status()
|
||||
async with aiofiles.open(str(temp_file_path), "wb") as f:
|
||||
async for chunk in response.aiter_bytes(chunk_size=8192):
|
||||
await f.write(chunk)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2.3 httpx.AsyncClient 반복 생성
|
||||
|
||||
여러 곳에서 `async with httpx.AsyncClient() as client:`를 사용하여 매번 새 클라이언트를 생성합니다.
|
||||
|
||||
**개선 방안 - 재사용 가능한 클라이언트**:
|
||||
```python
|
||||
# app/utils/http_client.py
|
||||
from contextlib import asynccontextmanager
|
||||
import httpx
|
||||
|
||||
_client: httpx.AsyncClient | None = None
|
||||
|
||||
async def get_http_client() -> httpx.AsyncClient:
|
||||
global _client
|
||||
if _client is None:
|
||||
_client = httpx.AsyncClient(timeout=30.0)
|
||||
return _client
|
||||
|
||||
async def close_http_client():
|
||||
global _client
|
||||
if _client:
|
||||
await _client.aclose()
|
||||
_client = None
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 심각도 낮음 - 선택적 개선
|
||||
|
||||
### 3.1 generate_video 엔드포인트의 다중 DB 조회 (video.py:109-191)
|
||||
|
||||
```python
|
||||
# 4개의 개별 쿼리가 순차적으로 실행됨
|
||||
project_result = await session.execute(select(Project).where(...))
|
||||
lyric_result = await session.execute(select(Lyric).where(...))
|
||||
song_result = await session.execute(select(Song).where(...))
|
||||
image_result = await session.execute(select(Image).where(...))
|
||||
```
|
||||
|
||||
**개선 방안 - 병렬 쿼리 실행**:
|
||||
```python
|
||||
import asyncio
|
||||
|
||||
project_task = session.execute(select(Project).where(Project.task_id == task_id))
|
||||
lyric_task = session.execute(select(Lyric).where(Lyric.task_id == task_id))
|
||||
song_task = session.execute(
|
||||
select(Song).where(Song.task_id == task_id).order_by(Song.created_at.desc()).limit(1)
|
||||
)
|
||||
image_task = session.execute(
|
||||
select(Image).where(Image.task_id == task_id).order_by(Image.img_order.asc())
|
||||
)
|
||||
|
||||
project_result, lyric_result, song_result, image_result = await asyncio.gather(
|
||||
project_task, lyric_task, song_task, image_task
|
||||
)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3.2 템플릿 조회 캐싱 미적용
|
||||
|
||||
`get_one_template_data_async()`가 매번 Creatomate API를 호출합니다.
|
||||
|
||||
**개선 방안 - 간단한 메모리 캐싱**:
|
||||
```python
|
||||
from functools import lru_cache
|
||||
from cachetools import TTLCache
|
||||
|
||||
_template_cache = TTLCache(maxsize=100, ttl=3600) # 1시간 캐시
|
||||
|
||||
async def get_one_template_data_async(self, template_id: str) -> dict:
|
||||
if template_id in _template_cache:
|
||||
return _template_cache[template_id]
|
||||
|
||||
url = f"{self.BASE_URL}/v1/templates/{template_id}"
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.get(url, headers=self.headers, timeout=30.0)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
|
||||
_template_cache[template_id] = data
|
||||
return data
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. 긍정적인 부분 (잘 구현된 패턴)
|
||||
|
||||
| 항목 | 상태 | 설명 |
|
||||
|------|------|------|
|
||||
| SQLAlchemy AsyncSession | O | `asyncmy` 드라이버와 `AsyncSessionLocal` 사용 |
|
||||
| 파일 I/O | O | `aiofiles` 사용으로 비동기 파일 처리 |
|
||||
| HTTP 클라이언트 | O | `httpx.AsyncClient` 사용 |
|
||||
| OpenAI API | O | `AsyncOpenAI` 클라이언트 사용 |
|
||||
| 백그라운드 태스크 | O | FastAPI `BackgroundTasks` 적절히 사용 |
|
||||
| 세션 관리 | O | 메인/워커 세션 분리로 이벤트 루프 충돌 방지 |
|
||||
| 연결 풀 설정 | O | `pool_size`, `pool_recycle`, `pool_pre_ping` 적절히 설정 |
|
||||
|
||||
---
|
||||
|
||||
## 5. 우선순위별 개선 권장 사항
|
||||
|
||||
| 우선순위 | 항목 | 예상 효과 |
|
||||
|----------|------|----------|
|
||||
| **1** | N+1 쿼리 문제 해결 | DB 부하 감소, 응답 속도 개선 |
|
||||
| **2** | 가사 생성 백그라운드 처리 | 동시 요청 처리 능력 향상 |
|
||||
| **3** | Creatomate 동기 메서드 제거 | 실수로 인한 블로킹 방지 |
|
||||
| **4** | 대용량 파일 스트리밍 다운로드 | 메모리 사용량 감소 |
|
||||
| **5** | 워커 세션 엔진 재사용 | 오버헤드 감소 |
|
||||
|
||||
---
|
||||
|
||||
## 분석 일자
|
||||
|
||||
2024-12-29
|
||||
# 비동기 처리 문제 분석 보고서
|
||||
|
||||
## 요약
|
||||
|
||||
전반적으로 이 프로젝트는 현대적인 비동기 아키텍처를 잘 구현하고 있습니다. 그러나 몇 가지 잠재적인 문제점과 개선 가능한 부분이 발견되었습니다.
|
||||
|
||||
---
|
||||
|
||||
## 1. 심각도 높음 - 즉시 개선 권장
|
||||
|
||||
### 1.1 N+1 쿼리 문제 (video.py:596-612)
|
||||
|
||||
```python
|
||||
# get_videos() 엔드포인트에서
|
||||
for video in videos:
|
||||
# 매 video마다 별도의 DB 쿼리 실행 - N+1 문제!
|
||||
project_result = await session.execute(
|
||||
select(Project).where(Project.id == video.project_id)
|
||||
)
|
||||
project = project_result.scalar_one_or_none()
|
||||
```
|
||||
|
||||
**문제점**: 비디오 목록 조회 시 각 비디오마다 별도의 Project 쿼리가 발생합니다. 10개 비디오 조회 시 11번의 DB 쿼리가 실행됩니다.
|
||||
|
||||
**개선 방안**:
|
||||
```python
|
||||
# selectinload를 사용한 eager loading
|
||||
from sqlalchemy.orm import selectinload
|
||||
|
||||
query = (
|
||||
select(Video)
|
||||
.options(selectinload(Video.project)) # relationship 필요
|
||||
.where(Video.id.in_(select(subquery.c.max_id)))
|
||||
.order_by(Video.created_at.desc())
|
||||
.offset(offset)
|
||||
.limit(pagination.page_size)
|
||||
)
|
||||
|
||||
# 또는 한 번에 project_ids 수집 후 일괄 조회
|
||||
project_ids = [v.project_id for v in videos]
|
||||
projects_result = await session.execute(
|
||||
select(Project).where(Project.id.in_(project_ids))
|
||||
)
|
||||
projects_map = {p.id: p for p in projects_result.scalars().all()}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 1.2 가사 생성 API의 블로킹 문제 (lyric.py:274-276)
|
||||
|
||||
```python
|
||||
# ChatGPT API 호출이 완료될 때까지 HTTP 응답이 블로킹됨
|
||||
print(f"[generate_lyric] ChatGPT generation started - task_id: {task_id}")
|
||||
result = await service.generate(prompt=prompt) # 수 초~수십 초 소요
|
||||
print(f"[generate_lyric] ChatGPT generation completed - task_id: {task_id}")
|
||||
```
|
||||
|
||||
**문제점**:
|
||||
- ChatGPT API 응답이 5-30초 이상 걸릴 수 있음
|
||||
- 이 시간 동안 클라이언트 연결이 유지되어야 함
|
||||
- 다수 동시 요청 시 worker 스레드 고갈 가능성
|
||||
|
||||
**개선 방안 (BackgroundTask 패턴)**:
|
||||
```python
|
||||
@router.post("/generate")
|
||||
async def generate_lyric(
|
||||
request_body: GenerateLyricRequest,
|
||||
background_tasks: BackgroundTasks,
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> GenerateLyricResponse:
|
||||
# DB에 processing 상태로 저장
|
||||
lyric = Lyric(status="processing", ...)
|
||||
session.add(lyric)
|
||||
await session.commit()
|
||||
|
||||
# 백그라운드에서 ChatGPT 호출
|
||||
background_tasks.add_task(
|
||||
generate_lyric_background,
|
||||
task_id=task_id,
|
||||
prompt=prompt,
|
||||
)
|
||||
|
||||
# 즉시 응답 반환
|
||||
return GenerateLyricResponse(
|
||||
success=True,
|
||||
task_id=task_id,
|
||||
message="가사 생성이 시작되었습니다. /status/{task_id}로 상태를 확인하세요.",
|
||||
)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 1.3 Creatomate 서비스의 동기/비동기 메서드 혼재 (creatomate.py)
|
||||
|
||||
**문제점**: 동기 메서드가 여전히 존재하여 실수로 async 컨텍스트에서 호출될 수 있습니다.
|
||||
|
||||
| 동기 메서드 | 비동기 메서드 |
|
||||
|------------|--------------|
|
||||
| `get_all_templates_data()` | 없음 |
|
||||
| `get_one_template_data()` | `get_one_template_data_async()` |
|
||||
| `make_creatomate_call()` | 없음 |
|
||||
| `make_creatomate_custom_call()` | `make_creatomate_custom_call_async()` |
|
||||
| `get_render_status()` | `get_render_status_async()` |
|
||||
|
||||
**개선 방안**:
|
||||
```python
|
||||
# 모든 HTTP 호출 메서드를 async로 통일
|
||||
async def get_all_templates_data(self) -> dict:
|
||||
url = f"{self.BASE_URL}/v1/templates"
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.get(url, headers=self.headers, timeout=30.0)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
# 동기 버전 제거 또는 deprecated 표시
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. 심각도 중간 - 개선 권장
|
||||
|
||||
### 2.1 백그라운드 태스크에서 매번 엔진 생성 (session.py:82-127)
|
||||
|
||||
```python
|
||||
@asynccontextmanager
|
||||
async def get_worker_session() -> AsyncGenerator[AsyncSession, None]:
|
||||
# 매 호출마다 새 엔진 생성 - 오버헤드 발생
|
||||
worker_engine = create_async_engine(
|
||||
url=db_settings.MYSQL_URL,
|
||||
poolclass=NullPool,
|
||||
...
|
||||
)
|
||||
```
|
||||
|
||||
**문제점**: 백그라운드 태스크가 빈번하게 호출되면 엔진 생성/소멸 오버헤드가 증가합니다.
|
||||
|
||||
**개선 방안**:
|
||||
```python
|
||||
# 모듈 레벨에서 워커 전용 엔진 생성
|
||||
_worker_engine = create_async_engine(
|
||||
url=db_settings.MYSQL_URL,
|
||||
poolclass=NullPool,
|
||||
)
|
||||
_WorkerSessionLocal = async_sessionmaker(bind=_worker_engine, ...)
|
||||
|
||||
@asynccontextmanager
|
||||
async def get_worker_session() -> AsyncGenerator[AsyncSession, None]:
|
||||
async with _WorkerSessionLocal() as session:
|
||||
try:
|
||||
yield session
|
||||
except Exception as e:
|
||||
await session.rollback()
|
||||
raise e
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2.2 대용량 파일 다운로드 시 메모리 사용 (video_task.py:49-54)
|
||||
|
||||
```python
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.get(video_url, timeout=180.0)
|
||||
response.raise_for_status()
|
||||
# 전체 파일을 메모리에 로드 - 대용량 영상 시 문제
|
||||
async with aiofiles.open(str(temp_file_path), "wb") as f:
|
||||
await f.write(response.content)
|
||||
```
|
||||
|
||||
**문제점**: 수백 MB 크기의 영상 파일을 한 번에 메모리에 로드합니다.
|
||||
|
||||
**개선 방안 - 스트리밍 다운로드**:
|
||||
```python
|
||||
async with httpx.AsyncClient() as client:
|
||||
async with client.stream("GET", video_url, timeout=180.0) as response:
|
||||
response.raise_for_status()
|
||||
async with aiofiles.open(str(temp_file_path), "wb") as f:
|
||||
async for chunk in response.aiter_bytes(chunk_size=8192):
|
||||
await f.write(chunk)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2.3 httpx.AsyncClient 반복 생성
|
||||
|
||||
여러 곳에서 `async with httpx.AsyncClient() as client:`를 사용하여 매번 새 클라이언트를 생성합니다.
|
||||
|
||||
**개선 방안 - 재사용 가능한 클라이언트**:
|
||||
```python
|
||||
# app/utils/http_client.py
|
||||
from contextlib import asynccontextmanager
|
||||
import httpx
|
||||
|
||||
_client: httpx.AsyncClient | None = None
|
||||
|
||||
async def get_http_client() -> httpx.AsyncClient:
|
||||
global _client
|
||||
if _client is None:
|
||||
_client = httpx.AsyncClient(timeout=30.0)
|
||||
return _client
|
||||
|
||||
async def close_http_client():
|
||||
global _client
|
||||
if _client:
|
||||
await _client.aclose()
|
||||
_client = None
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 심각도 낮음 - 선택적 개선
|
||||
|
||||
### 3.1 generate_video 엔드포인트의 다중 DB 조회 (video.py:109-191)
|
||||
|
||||
```python
|
||||
# 4개의 개별 쿼리가 순차적으로 실행됨
|
||||
project_result = await session.execute(select(Project).where(...))
|
||||
lyric_result = await session.execute(select(Lyric).where(...))
|
||||
song_result = await session.execute(select(Song).where(...))
|
||||
image_result = await session.execute(select(Image).where(...))
|
||||
```
|
||||
|
||||
**개선 방안 - 병렬 쿼리 실행**:
|
||||
```python
|
||||
import asyncio
|
||||
|
||||
project_task = session.execute(select(Project).where(Project.task_id == task_id))
|
||||
lyric_task = session.execute(select(Lyric).where(Lyric.task_id == task_id))
|
||||
song_task = session.execute(
|
||||
select(Song).where(Song.task_id == task_id).order_by(Song.created_at.desc()).limit(1)
|
||||
)
|
||||
image_task = session.execute(
|
||||
select(Image).where(Image.task_id == task_id).order_by(Image.img_order.asc())
|
||||
)
|
||||
|
||||
project_result, lyric_result, song_result, image_result = await asyncio.gather(
|
||||
project_task, lyric_task, song_task, image_task
|
||||
)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3.2 템플릿 조회 캐싱 미적용
|
||||
|
||||
`get_one_template_data_async()`가 매번 Creatomate API를 호출합니다.
|
||||
|
||||
**개선 방안 - 간단한 메모리 캐싱**:
|
||||
```python
|
||||
from functools import lru_cache
|
||||
from cachetools import TTLCache
|
||||
|
||||
_template_cache = TTLCache(maxsize=100, ttl=3600) # 1시간 캐시
|
||||
|
||||
async def get_one_template_data_async(self, template_id: str) -> dict:
|
||||
if template_id in _template_cache:
|
||||
return _template_cache[template_id]
|
||||
|
||||
url = f"{self.BASE_URL}/v1/templates/{template_id}"
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.get(url, headers=self.headers, timeout=30.0)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
|
||||
_template_cache[template_id] = data
|
||||
return data
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. 긍정적인 부분 (잘 구현된 패턴)
|
||||
|
||||
| 항목 | 상태 | 설명 |
|
||||
|------|------|------|
|
||||
| SQLAlchemy AsyncSession | O | `asyncmy` 드라이버와 `AsyncSessionLocal` 사용 |
|
||||
| 파일 I/O | O | `aiofiles` 사용으로 비동기 파일 처리 |
|
||||
| HTTP 클라이언트 | O | `httpx.AsyncClient` 사용 |
|
||||
| OpenAI API | O | `AsyncOpenAI` 클라이언트 사용 |
|
||||
| 백그라운드 태스크 | O | FastAPI `BackgroundTasks` 적절히 사용 |
|
||||
| 세션 관리 | O | 메인/워커 세션 분리로 이벤트 루프 충돌 방지 |
|
||||
| 연결 풀 설정 | O | `pool_size`, `pool_recycle`, `pool_pre_ping` 적절히 설정 |
|
||||
|
||||
---
|
||||
|
||||
## 5. 우선순위별 개선 권장 사항
|
||||
|
||||
| 우선순위 | 항목 | 예상 효과 |
|
||||
|----------|------|----------|
|
||||
| **1** | N+1 쿼리 문제 해결 | DB 부하 감소, 응답 속도 개선 |
|
||||
| **2** | 가사 생성 백그라운드 처리 | 동시 요청 처리 능력 향상 |
|
||||
| **3** | Creatomate 동기 메서드 제거 | 실수로 인한 블로킹 방지 |
|
||||
| **4** | 대용량 파일 스트리밍 다운로드 | 메모리 사용량 감소 |
|
||||
| **5** | 워커 세션 엔진 재사용 | 오버헤드 감소 |
|
||||
|
||||
---
|
||||
|
||||
## 분석 일자
|
||||
|
||||
2024-12-29
|
||||
+1781
-1781
File diff suppressed because it is too large.
Load diff
+1488
-1488
File diff suppressed because it is too large.
Load diff
@@ -1,82 +1,82 @@
|
||||
-- input_history 테이블
|
||||
CREATE TABLE input_history (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
customer_name VARCHAR(255) NOT NULL,
|
||||
region VARCHAR(100) NOT NULL,
|
||||
task_id CHAR(36) NOT NULL,
|
||||
detail_region_info TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- upload_img_url 테이블
|
||||
CREATE TABLE upload_img_url (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
task_id CHAR(36) NOT NULL,
|
||||
img_uid INT NOT NULL,
|
||||
img_url VARCHAR(2048) NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (task_id) REFERENCES input_history(task_id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- lyrics 테이블
|
||||
CREATE TABLE lyrics (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
input_history_id INT NOT NULL,
|
||||
task_id CHAR(36) NOT NULL,
|
||||
status VARCHAR(50) NOT NULL,
|
||||
lyrics_prompt TEXT NOT NULL,
|
||||
lyrics_result LONGTEXT NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (input_history_id) REFERENCES input_history(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- song 테이블
|
||||
CREATE TABLE song (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
input_history_id INT NOT NULL,
|
||||
lyrics_id INT NOT NULL,
|
||||
task_id CHAR(36) NOT NULL,
|
||||
status VARCHAR(50) NOT NULL,
|
||||
song_prompt TEXT NOT NULL,
|
||||
song_result_url_1 VARCHAR(2048),
|
||||
song_result_url_2 VARCHAR(2048),
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (input_history_id) REFERENCES input_history(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (lyrics_id) REFERENCES lyrics(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- creatomate_result_url 테이블
|
||||
CREATE TABLE creatomate_result_url (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
input_history_id INT NOT NULL,
|
||||
song_id INT NOT NULL,
|
||||
task_id CHAR(36) NOT NULL,
|
||||
status VARCHAR(50) NOT NULL,
|
||||
result_movie_url VARCHAR(2048),
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (input_history_id) REFERENCES input_history(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (song_id) REFERENCES song(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- ===== 인덱스 추가 (쿼리 성능 최적화) =====
|
||||
|
||||
-- input_history
|
||||
CREATE INDEX idx_input_history_task_id ON input_history(task_id);
|
||||
|
||||
-- upload_img_url (task_id 인덱스 + 복합 인덱스)
|
||||
CREATE INDEX idx_upload_img_url_task_id ON upload_img_url(task_id);
|
||||
CREATE INDEX idx_upload_img_url_task_id_img_uid ON upload_img_url(task_id, img_uid);
|
||||
|
||||
-- lyrics (input_history_id + task_id 인덱스)
|
||||
CREATE INDEX idx_lyrics_input_history_id ON lyrics(input_history_id);
|
||||
CREATE INDEX idx_lyrics_task_id ON lyrics(task_id);
|
||||
|
||||
-- song (input_history_id + lyrics_id + task_id 인덱스)
|
||||
CREATE INDEX idx_song_input_history_id ON song(input_history_id);
|
||||
CREATE INDEX idx_song_lyrics_id ON song(lyrics_id);
|
||||
CREATE INDEX idx_song_task_id ON song(task_id);
|
||||
|
||||
-- creatomate_result_url (input_history_id + song_id + task_id 인덱스)
|
||||
CREATE INDEX idx_creatomate_input_history_id ON creatomate_result_url(input_history_id);
|
||||
CREATE INDEX idx_creatomate_song_id ON creatomate_result_url(song_id);
|
||||
-- input_history 테이블
|
||||
CREATE TABLE input_history (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
customer_name VARCHAR(255) NOT NULL,
|
||||
region VARCHAR(100) NOT NULL,
|
||||
task_id CHAR(36) NOT NULL,
|
||||
detail_region_info TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- upload_img_url 테이블
|
||||
CREATE TABLE upload_img_url (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
task_id CHAR(36) NOT NULL,
|
||||
img_uid INT NOT NULL,
|
||||
img_url VARCHAR(2048) NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (task_id) REFERENCES input_history(task_id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- lyrics 테이블
|
||||
CREATE TABLE lyrics (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
input_history_id INT NOT NULL,
|
||||
task_id CHAR(36) NOT NULL,
|
||||
status VARCHAR(50) NOT NULL,
|
||||
lyrics_prompt TEXT NOT NULL,
|
||||
lyrics_result LONGTEXT NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (input_history_id) REFERENCES input_history(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- song 테이블
|
||||
CREATE TABLE song (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
input_history_id INT NOT NULL,
|
||||
lyrics_id INT NOT NULL,
|
||||
task_id CHAR(36) NOT NULL,
|
||||
status VARCHAR(50) NOT NULL,
|
||||
song_prompt TEXT NOT NULL,
|
||||
song_result_url_1 VARCHAR(2048),
|
||||
song_result_url_2 VARCHAR(2048),
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (input_history_id) REFERENCES input_history(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (lyrics_id) REFERENCES lyrics(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- creatomate_result_url 테이블
|
||||
CREATE TABLE creatomate_result_url (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
input_history_id INT NOT NULL,
|
||||
song_id INT NOT NULL,
|
||||
task_id CHAR(36) NOT NULL,
|
||||
status VARCHAR(50) NOT NULL,
|
||||
result_movie_url VARCHAR(2048),
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (input_history_id) REFERENCES input_history(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (song_id) REFERENCES song(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- ===== 인덱스 추가 (쿼리 성능 최적화) =====
|
||||
|
||||
-- input_history
|
||||
CREATE INDEX idx_input_history_task_id ON input_history(task_id);
|
||||
|
||||
-- upload_img_url (task_id 인덱스 + 복합 인덱스)
|
||||
CREATE INDEX idx_upload_img_url_task_id ON upload_img_url(task_id);
|
||||
CREATE INDEX idx_upload_img_url_task_id_img_uid ON upload_img_url(task_id, img_uid);
|
||||
|
||||
-- lyrics (input_history_id + task_id 인덱스)
|
||||
CREATE INDEX idx_lyrics_input_history_id ON lyrics(input_history_id);
|
||||
CREATE INDEX idx_lyrics_task_id ON lyrics(task_id);
|
||||
|
||||
-- song (input_history_id + lyrics_id + task_id 인덱스)
|
||||
CREATE INDEX idx_song_input_history_id ON song(input_history_id);
|
||||
CREATE INDEX idx_song_lyrics_id ON song(lyrics_id);
|
||||
CREATE INDEX idx_song_task_id ON song(task_id);
|
||||
|
||||
-- creatomate_result_url (input_history_id + song_id + task_id 인덱스)
|
||||
CREATE INDEX idx_creatomate_input_history_id ON creatomate_result_url(input_history_id);
|
||||
CREATE INDEX idx_creatomate_song_id ON creatomate_result_url(song_id);
|
||||
CREATE INDEX idx_creatomate_task_id ON creatomate_result_url(task_id);
|
||||
@@ -1,83 +1,83 @@
|
||||
-- input_history 테이블
|
||||
CREATE TABLE input_history (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
customer_name VARCHAR(255) NOT NULL,
|
||||
region VARCHAR(100) NOT NULL,
|
||||
task_id CHAR(36) NOT NULL UNIQUE, -- 유니크 UUID
|
||||
detail_region_info TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- upload_img_url 테이블
|
||||
CREATE TABLE upload_img_url (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
task_id CHAR(36) NOT NULL, -- input_history와 연결
|
||||
img_uid INT NOT NULL,
|
||||
img_url VARCHAR(2048) NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE KEY unique_img_task_image (task_id, img_uid),
|
||||
FOREIGN KEY (task_id) REFERENCES input_history(task_id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- lyrics 테이블
|
||||
CREATE TABLE lyrics (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
input_history_id INT NOT NULL,
|
||||
task_id CHAR(36) NOT NULL UNIQUE,
|
||||
status VARCHAR(50) NOT NULL,
|
||||
lyrics_prompt TEXT NOT NULL,
|
||||
lyrics_result LONGTEXT NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (input_history_id) REFERENCES input_history(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- song 테이블
|
||||
CREATE TABLE song (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
input_history_id INT NOT NULL,
|
||||
lyrics_id INT NOT NULL,
|
||||
task_id CHAR(36) NOT NULL UNIQUE,
|
||||
status VARCHAR(50) NOT NULL,
|
||||
song_prompt TEXT NOT NULL,
|
||||
song_result_url_1 VARCHAR(2048),
|
||||
song_result_url_2 VARCHAR(2048),
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (input_history_id) REFERENCES input_history(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (lyrics_id) REFERENCES lyrics(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- creatomate_result_url 테이블
|
||||
CREATE TABLE creatomate_result_url (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
input_history_id INT NOT NULL,
|
||||
song_id INT NOT NULL,
|
||||
task_id CHAR(36) NOT NULL UNIQUE,
|
||||
status VARCHAR(50) NOT NULL,
|
||||
result_movie_url VARCHAR(2048),
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (input_history_id) REFERENCES input_history(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (song_id) REFERENCES song(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- ===== 인덱스 추가 (쿼리 성능 최적화) =====
|
||||
|
||||
-- input_history
|
||||
CREATE INDEX idx_input_history_task_id ON input_history(task_id);
|
||||
|
||||
-- upload_img_url (task_id 인덱스 + 복합 인덱스)
|
||||
CREATE INDEX idx_upload_img_url_task_id ON upload_img_url(task_id);
|
||||
CREATE INDEX idx_upload_img_url_task_id_img_uid ON upload_img_url(task_id, img_uid);
|
||||
|
||||
-- lyrics (input_history_id + task_id 인덱스)
|
||||
CREATE INDEX idx_lyrics_input_history_id ON lyrics(input_history_id);
|
||||
CREATE INDEX idx_lyrics_task_id ON lyrics(task_id);
|
||||
|
||||
-- song (input_history_id + lyrics_id + task_id 인덱스)
|
||||
CREATE INDEX idx_song_input_history_id ON song(input_history_id);
|
||||
CREATE INDEX idx_song_lyrics_id ON song(lyrics_id);
|
||||
CREATE INDEX idx_song_task_id ON song(task_id);
|
||||
|
||||
-- creatomate_result_url (input_history_id + song_id + task_id 인덱스)
|
||||
CREATE INDEX idx_creatomate_input_history_id ON creatomate_result_url(input_history_id);
|
||||
CREATE INDEX idx_creatomate_song_id ON creatomate_result_url(song_id);
|
||||
-- input_history 테이블
|
||||
CREATE TABLE input_history (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
customer_name VARCHAR(255) NOT NULL,
|
||||
region VARCHAR(100) NOT NULL,
|
||||
task_id CHAR(36) NOT NULL UNIQUE, -- 유니크 UUID
|
||||
detail_region_info TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- upload_img_url 테이블
|
||||
CREATE TABLE upload_img_url (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
task_id CHAR(36) NOT NULL, -- input_history와 연결
|
||||
img_uid INT NOT NULL,
|
||||
img_url VARCHAR(2048) NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE KEY unique_img_task_image (task_id, img_uid),
|
||||
FOREIGN KEY (task_id) REFERENCES input_history(task_id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- lyrics 테이블
|
||||
CREATE TABLE lyrics (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
input_history_id INT NOT NULL,
|
||||
task_id CHAR(36) NOT NULL UNIQUE,
|
||||
status VARCHAR(50) NOT NULL,
|
||||
lyrics_prompt TEXT NOT NULL,
|
||||
lyrics_result LONGTEXT NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (input_history_id) REFERENCES input_history(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- song 테이블
|
||||
CREATE TABLE song (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
input_history_id INT NOT NULL,
|
||||
lyrics_id INT NOT NULL,
|
||||
task_id CHAR(36) NOT NULL UNIQUE,
|
||||
status VARCHAR(50) NOT NULL,
|
||||
song_prompt TEXT NOT NULL,
|
||||
song_result_url_1 VARCHAR(2048),
|
||||
song_result_url_2 VARCHAR(2048),
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (input_history_id) REFERENCES input_history(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (lyrics_id) REFERENCES lyrics(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- creatomate_result_url 테이블
|
||||
CREATE TABLE creatomate_result_url (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
input_history_id INT NOT NULL,
|
||||
song_id INT NOT NULL,
|
||||
task_id CHAR(36) NOT NULL UNIQUE,
|
||||
status VARCHAR(50) NOT NULL,
|
||||
result_movie_url VARCHAR(2048),
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (input_history_id) REFERENCES input_history(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (song_id) REFERENCES song(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- ===== 인덱스 추가 (쿼리 성능 최적화) =====
|
||||
|
||||
-- input_history
|
||||
CREATE INDEX idx_input_history_task_id ON input_history(task_id);
|
||||
|
||||
-- upload_img_url (task_id 인덱스 + 복합 인덱스)
|
||||
CREATE INDEX idx_upload_img_url_task_id ON upload_img_url(task_id);
|
||||
CREATE INDEX idx_upload_img_url_task_id_img_uid ON upload_img_url(task_id, img_uid);
|
||||
|
||||
-- lyrics (input_history_id + task_id 인덱스)
|
||||
CREATE INDEX idx_lyrics_input_history_id ON lyrics(input_history_id);
|
||||
CREATE INDEX idx_lyrics_task_id ON lyrics(task_id);
|
||||
|
||||
-- song (input_history_id + lyrics_id + task_id 인덱스)
|
||||
CREATE INDEX idx_song_input_history_id ON song(input_history_id);
|
||||
CREATE INDEX idx_song_lyrics_id ON song(lyrics_id);
|
||||
CREATE INDEX idx_song_task_id ON song(task_id);
|
||||
|
||||
-- creatomate_result_url (input_history_id + song_id + task_id 인덱스)
|
||||
CREATE INDEX idx_creatomate_input_history_id ON creatomate_result_url(input_history_id);
|
||||
CREATE INDEX idx_creatomate_song_id ON creatomate_result_url(song_id);
|
||||
CREATE INDEX idx_creatomate_task_id ON creatomate_result_url(task_id);
|
||||
+382
-382
@@ -1,382 +1,382 @@
|
||||
# Pydantic ConfigDict 사용 매뉴얼
|
||||
|
||||
## 개요
|
||||
|
||||
Pydantic v2에서 `ConfigDict`는 모델의 유효성 검사, 직렬화, JSON 스키마 생성 등의 동작을 제어하는 설정을 정의하는 TypedDict입니다.
|
||||
|
||||
> Pydantic v1의 `class Config`는 더 이상 권장되지 않으며, `ConfigDict`를 사용해야 합니다.
|
||||
|
||||
## 기본 사용법
|
||||
|
||||
```python
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
class MyModel(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
str_strip_whitespace=True,
|
||||
strict=True
|
||||
)
|
||||
|
||||
name: str
|
||||
age: int
|
||||
```
|
||||
|
||||
## 설정 옵션 전체 목록
|
||||
|
||||
### 문자열 처리
|
||||
|
||||
| 옵션 | 타입 | 기본값 | 설명 |
|
||||
|------|------|--------|------|
|
||||
| `str_to_lower` | `bool` | `False` | 문자열을 소문자로 변환 |
|
||||
| `str_to_upper` | `bool` | `False` | 문자열을 대문자로 변환 |
|
||||
| `str_strip_whitespace` | `bool` | `False` | 문자열 앞뒤 공백 제거 |
|
||||
| `str_min_length` | `int \| None` | `None` | 문자열 최소 길이 |
|
||||
| `str_max_length` | `int \| None` | `None` | 문자열 최대 길이 |
|
||||
|
||||
**예시:**
|
||||
```python
|
||||
class UserInput(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
str_strip_whitespace=True,
|
||||
str_to_lower=True,
|
||||
str_min_length=1,
|
||||
str_max_length=100
|
||||
)
|
||||
|
||||
username: str
|
||||
|
||||
user = UserInput(username=" HELLO ")
|
||||
print(user.username) # "hello"
|
||||
```
|
||||
|
||||
### 유효성 검사
|
||||
|
||||
| 옵션 | 타입 | 기본값 | 설명 |
|
||||
|------|------|--------|------|
|
||||
| `strict` | `bool` | `False` | 엄격한 타입 검사 활성화 (타입 강제 변환 비활성화) |
|
||||
| `validate_assignment` | `bool` | `False` | 속성 할당 시 유효성 검사 수행 |
|
||||
| `validate_default` | `bool` | `False` | 기본값도 유효성 검사 수행 |
|
||||
| `validate_return` | `bool` | `False` | 반환값 유효성 검사 |
|
||||
| `revalidate_instances` | `Literal['always', 'never', 'subclass-instances']` | `'never'` | 모델 인스턴스 재검증 시점 |
|
||||
| `arbitrary_types_allowed` | `bool` | `False` | Pydantic이 지원하지 않는 타입 허용 |
|
||||
|
||||
**예시 - strict 모드:**
|
||||
```python
|
||||
class StrictModel(BaseModel):
|
||||
model_config = ConfigDict(strict=True)
|
||||
|
||||
count: int
|
||||
|
||||
# strict=False (기본값): "123" -> 123 자동 변환
|
||||
# strict=True: "123" 입력 시 ValidationError 발생
|
||||
```
|
||||
|
||||
**예시 - validate_assignment:**
|
||||
```python
|
||||
class User(BaseModel):
|
||||
model_config = ConfigDict(validate_assignment=True)
|
||||
|
||||
age: int
|
||||
|
||||
user = User(age=25)
|
||||
user.age = "invalid" # ValidationError 발생
|
||||
```
|
||||
|
||||
### Extra 필드 처리
|
||||
|
||||
| 옵션 | 타입 | 기본값 | 설명 |
|
||||
|------|------|--------|------|
|
||||
| `extra` | `'allow' \| 'ignore' \| 'forbid'` | `'ignore'` | 추가 필드 처리 방식 |
|
||||
|
||||
**값 설명:**
|
||||
- `'ignore'`: 추가 필드 무시 (기본값)
|
||||
- `'allow'`: 추가 필드 허용, `__pydantic_extra__`에 저장
|
||||
- `'forbid'`: 추가 필드 입력 시 에러 발생
|
||||
|
||||
**예시:**
|
||||
```python
|
||||
class AllowExtra(BaseModel):
|
||||
model_config = ConfigDict(extra='allow')
|
||||
|
||||
name: str
|
||||
|
||||
data = AllowExtra(name="John", unknown_field="value")
|
||||
print(data.__pydantic_extra__) # {'unknown_field': 'value'}
|
||||
|
||||
class ForbidExtra(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
|
||||
name: str
|
||||
|
||||
ForbidExtra(name="John", unknown="value") # ValidationError 발생
|
||||
```
|
||||
|
||||
### 불변성 (Immutability)
|
||||
|
||||
| 옵션 | 타입 | 기본값 | 설명 |
|
||||
|------|------|--------|------|
|
||||
| `frozen` | `bool` | `False` | 모델을 불변(immutable)으로 만듦, `__hash__()` 구현 |
|
||||
|
||||
**예시:**
|
||||
```python
|
||||
class ImmutableUser(BaseModel):
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
name: str
|
||||
age: int
|
||||
|
||||
user = ImmutableUser(name="John", age=30)
|
||||
user.age = 31 # 에러 발생: Instance is frozen
|
||||
|
||||
# frozen=True이면 해시 가능
|
||||
users_set = {user} # 정상 작동
|
||||
```
|
||||
|
||||
### 별칭 (Alias) 설정
|
||||
|
||||
| 옵션 | 타입 | 기본값 | 설명 |
|
||||
|------|------|--------|------|
|
||||
| `populate_by_name` | `bool` | `False` | 필드명과 별칭 모두로 값 설정 허용 (deprecated) |
|
||||
| `validate_by_alias` | `bool` | `True` | 별칭으로 필드 값 설정 허용 |
|
||||
| `validate_by_name` | `bool` | `False` | 별칭이 있어도 필드명으로 값 설정 허용 |
|
||||
| `serialize_by_alias` | `bool` | `False` | 직렬화 시 별칭 사용 |
|
||||
| `alias_generator` | `Callable[[str], str] \| None` | `None` | 별칭 자동 생성 함수 |
|
||||
| `loc_by_alias` | `bool` | `True` | 에러 위치에 별칭 사용 |
|
||||
|
||||
**예시:**
|
||||
```python
|
||||
from pydantic import Field
|
||||
|
||||
class APIResponse(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
validate_by_alias=True,
|
||||
validate_by_name=True,
|
||||
serialize_by_alias=True
|
||||
)
|
||||
|
||||
user_name: str = Field(alias="userName")
|
||||
|
||||
# 둘 다 가능
|
||||
response1 = APIResponse(userName="John")
|
||||
response2 = APIResponse(user_name="John")
|
||||
|
||||
print(response1.model_dump(by_alias=True)) # {"userName": "John"}
|
||||
```
|
||||
|
||||
**예시 - alias_generator:**
|
||||
```python
|
||||
def to_camel(name: str) -> str:
|
||||
parts = name.split('_')
|
||||
return parts[0] + ''.join(word.capitalize() for word in parts[1:])
|
||||
|
||||
class CamelModel(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
alias_generator=to_camel,
|
||||
serialize_by_alias=True
|
||||
)
|
||||
|
||||
first_name: str
|
||||
last_name: str
|
||||
|
||||
data = CamelModel(firstName="John", lastName="Doe")
|
||||
print(data.model_dump(by_alias=True))
|
||||
# {"firstName": "John", "lastName": "Doe"}
|
||||
```
|
||||
|
||||
### JSON 스키마
|
||||
|
||||
| 옵션 | 타입 | 기본값 | 설명 |
|
||||
|------|------|--------|------|
|
||||
| `title` | `str \| None` | `None` | JSON 스키마 타이틀 |
|
||||
| `json_schema_extra` | `dict \| Callable \| None` | `None` | JSON 스키마에 추가할 정보 |
|
||||
| `json_schema_serialization_defaults_required` | `bool` | `False` | 직렬화 스키마에서 기본값이 있는 필드도 required로 표시 |
|
||||
| `json_schema_mode_override` | `Literal['validation', 'serialization', None]` | `None` | JSON 스키마 모드 강제 지정 |
|
||||
|
||||
**예시 - json_schema_extra:**
|
||||
```python
|
||||
class Product(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
title="상품 정보",
|
||||
json_schema_extra={
|
||||
"example": {
|
||||
"name": "노트북",
|
||||
"price": 1500000
|
||||
},
|
||||
"description": "상품 데이터를 나타내는 모델"
|
||||
}
|
||||
)
|
||||
|
||||
name: str
|
||||
price: int
|
||||
|
||||
# OpenAPI/Swagger 문서에 예시가 표시됨
|
||||
```
|
||||
|
||||
**예시 - Callable json_schema_extra:**
|
||||
```python
|
||||
def add_examples(schema: dict) -> dict:
|
||||
schema["examples"] = [
|
||||
{"name": "예시1", "value": 100},
|
||||
{"name": "예시2", "value": 200}
|
||||
]
|
||||
return schema
|
||||
|
||||
class DynamicSchema(BaseModel):
|
||||
model_config = ConfigDict(json_schema_extra=add_examples)
|
||||
|
||||
name: str
|
||||
value: int
|
||||
```
|
||||
|
||||
### ORM/속성 모드
|
||||
|
||||
| 옵션 | 타입 | 기본값 | 설명 |
|
||||
|------|------|--------|------|
|
||||
| `from_attributes` | `bool` | `False` | 객체 속성에서 모델 생성 허용 (SQLAlchemy 등) |
|
||||
|
||||
**예시:**
|
||||
```python
|
||||
class UserORM:
|
||||
def __init__(self, name: str, age: int):
|
||||
self.name = name
|
||||
self.age = age
|
||||
|
||||
class UserModel(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
name: str
|
||||
age: int
|
||||
|
||||
orm_user = UserORM(name="John", age=30)
|
||||
pydantic_user = UserModel.model_validate(orm_user)
|
||||
print(pydantic_user) # name='John' age=30
|
||||
```
|
||||
|
||||
### Enum 처리
|
||||
|
||||
| 옵션 | 타입 | 기본값 | 설명 |
|
||||
|------|------|--------|------|
|
||||
| `use_enum_values` | `bool` | `False` | Enum 대신 값(value)으로 저장 |
|
||||
|
||||
**예시:**
|
||||
```python
|
||||
from enum import Enum
|
||||
|
||||
class Status(Enum):
|
||||
ACTIVE = "active"
|
||||
INACTIVE = "inactive"
|
||||
|
||||
class User(BaseModel):
|
||||
model_config = ConfigDict(use_enum_values=True)
|
||||
|
||||
status: Status
|
||||
|
||||
user = User(status=Status.ACTIVE)
|
||||
print(user.status) # "active" (문자열)
|
||||
print(type(user.status)) # <class 'str'>
|
||||
|
||||
# use_enum_values=False (기본값)이면
|
||||
# user.status는 Status.ACTIVE (Enum 객체)
|
||||
```
|
||||
|
||||
### 직렬화 설정
|
||||
|
||||
| 옵션 | 타입 | 기본값 | 설명 |
|
||||
|------|------|--------|------|
|
||||
| `ser_json_timedelta` | `'iso8601' \| 'float'` | `'iso8601'` | timedelta JSON 직렬화 형식 |
|
||||
| `ser_json_bytes` | `'utf8' \| 'base64' \| 'hex'` | `'utf8'` | bytes JSON 직렬화 인코딩 |
|
||||
| `ser_json_inf_nan` | `'null' \| 'constants' \| 'strings'` | `'null'` | 무한대/NaN JSON 직렬화 형식 |
|
||||
|
||||
### 숫자/Float 설정
|
||||
|
||||
| 옵션 | 타입 | 기본값 | 설명 |
|
||||
|------|------|--------|------|
|
||||
| `allow_inf_nan` | `bool` | `True` | float에서 무한대/NaN 허용 |
|
||||
| `coerce_numbers_to_str` | `bool` | `False` | 숫자를 문자열로 강제 변환 허용 |
|
||||
|
||||
### 기타 설정
|
||||
|
||||
| 옵션 | 타입 | 기본값 | 설명 |
|
||||
|------|------|--------|------|
|
||||
| `protected_namespaces` | `tuple[str, ...]` | `('model_',)` | 보호할 필드명 접두사 |
|
||||
| `hide_input_in_errors` | `bool` | `False` | 에러 메시지에서 입력값 숨김 |
|
||||
| `defer_build` | `bool` | `False` | validator/serializer 빌드 지연 |
|
||||
| `use_attribute_docstrings` | `bool` | `False` | 속성 docstring을 필드 설명으로 사용 |
|
||||
| `regex_engine` | `'rust-regex' \| 'python-re'` | `'rust-regex'` | 정규식 엔진 선택 |
|
||||
| `validation_error_cause` | `bool` | `False` | Python 예외를 에러 원인에 포함 |
|
||||
|
||||
## 설정 상속
|
||||
|
||||
자식 모델은 부모 모델의 `model_config`를 상속받습니다.
|
||||
|
||||
```python
|
||||
class ParentModel(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
str_strip_whitespace=True,
|
||||
extra='allow'
|
||||
)
|
||||
|
||||
name: str
|
||||
|
||||
class ChildModel(ParentModel):
|
||||
model_config = ConfigDict(
|
||||
frozen=True # 부모 설정 + frozen=True
|
||||
)
|
||||
|
||||
age: int
|
||||
|
||||
# ChildModel은 str_strip_whitespace=True, extra='allow', frozen=True
|
||||
```
|
||||
|
||||
## FastAPI와 함께 사용
|
||||
|
||||
FastAPI에서 요청/응답 스키마로 사용할 때 특히 유용합니다.
|
||||
|
||||
```python
|
||||
from fastapi import FastAPI
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
class CreateUserRequest(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
str_strip_whitespace=True,
|
||||
json_schema_extra={
|
||||
"example": {
|
||||
"username": "johndoe",
|
||||
"email": "john@example.com"
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
username: str = Field(..., min_length=3, max_length=50)
|
||||
email: str
|
||||
|
||||
class UserResponse(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
from_attributes=True, # ORM 객체에서 변환 가능
|
||||
serialize_by_alias=True
|
||||
)
|
||||
|
||||
id: int
|
||||
user_name: str = Field(alias="userName")
|
||||
|
||||
@app.post("/users", response_model=UserResponse)
|
||||
async def create_user(user: CreateUserRequest):
|
||||
# user.username은 자동으로 공백이 제거됨
|
||||
...
|
||||
```
|
||||
|
||||
## 주의사항
|
||||
|
||||
1. **v1에서 마이그레이션**: `class Config`는 deprecated입니다. `model_config = ConfigDict(...)`를 사용하세요.
|
||||
|
||||
2. **populate_by_name은 deprecated**: `validate_by_alias`와 `validate_by_name`을 함께 사용하세요.
|
||||
|
||||
3. **json_encoders는 deprecated**: 커스텀 직렬화가 필요하면 `@field_serializer` 데코레이터를 사용하세요.
|
||||
|
||||
## 참고 자료
|
||||
|
||||
- [Pydantic Configuration API 공식 문서](https://docs.pydantic.dev/latest/api/config/)
|
||||
- [Pydantic Models 개념](https://docs.pydantic.dev/latest/concepts/models/)
|
||||
- [Pydantic Migration Guide](https://docs.pydantic.dev/latest/migration/)
|
||||
# Pydantic ConfigDict 사용 매뉴얼
|
||||
|
||||
## 개요
|
||||
|
||||
Pydantic v2에서 `ConfigDict`는 모델의 유효성 검사, 직렬화, JSON 스키마 생성 등의 동작을 제어하는 설정을 정의하는 TypedDict입니다.
|
||||
|
||||
> Pydantic v1의 `class Config`는 더 이상 권장되지 않으며, `ConfigDict`를 사용해야 합니다.
|
||||
|
||||
## 기본 사용법
|
||||
|
||||
```python
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
class MyModel(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
str_strip_whitespace=True,
|
||||
strict=True
|
||||
)
|
||||
|
||||
name: str
|
||||
age: int
|
||||
```
|
||||
|
||||
## 설정 옵션 전체 목록
|
||||
|
||||
### 문자열 처리
|
||||
|
||||
| 옵션 | 타입 | 기본값 | 설명 |
|
||||
|------|------|--------|------|
|
||||
| `str_to_lower` | `bool` | `False` | 문자열을 소문자로 변환 |
|
||||
| `str_to_upper` | `bool` | `False` | 문자열을 대문자로 변환 |
|
||||
| `str_strip_whitespace` | `bool` | `False` | 문자열 앞뒤 공백 제거 |
|
||||
| `str_min_length` | `int \| None` | `None` | 문자열 최소 길이 |
|
||||
| `str_max_length` | `int \| None` | `None` | 문자열 최대 길이 |
|
||||
|
||||
**예시:**
|
||||
```python
|
||||
class UserInput(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
str_strip_whitespace=True,
|
||||
str_to_lower=True,
|
||||
str_min_length=1,
|
||||
str_max_length=100
|
||||
)
|
||||
|
||||
username: str
|
||||
|
||||
user = UserInput(username=" HELLO ")
|
||||
print(user.username) # "hello"
|
||||
```
|
||||
|
||||
### 유효성 검사
|
||||
|
||||
| 옵션 | 타입 | 기본값 | 설명 |
|
||||
|------|------|--------|------|
|
||||
| `strict` | `bool` | `False` | 엄격한 타입 검사 활성화 (타입 강제 변환 비활성화) |
|
||||
| `validate_assignment` | `bool` | `False` | 속성 할당 시 유효성 검사 수행 |
|
||||
| `validate_default` | `bool` | `False` | 기본값도 유효성 검사 수행 |
|
||||
| `validate_return` | `bool` | `False` | 반환값 유효성 검사 |
|
||||
| `revalidate_instances` | `Literal['always', 'never', 'subclass-instances']` | `'never'` | 모델 인스턴스 재검증 시점 |
|
||||
| `arbitrary_types_allowed` | `bool` | `False` | Pydantic이 지원하지 않는 타입 허용 |
|
||||
|
||||
**예시 - strict 모드:**
|
||||
```python
|
||||
class StrictModel(BaseModel):
|
||||
model_config = ConfigDict(strict=True)
|
||||
|
||||
count: int
|
||||
|
||||
# strict=False (기본값): "123" -> 123 자동 변환
|
||||
# strict=True: "123" 입력 시 ValidationError 발생
|
||||
```
|
||||
|
||||
**예시 - validate_assignment:**
|
||||
```python
|
||||
class User(BaseModel):
|
||||
model_config = ConfigDict(validate_assignment=True)
|
||||
|
||||
age: int
|
||||
|
||||
user = User(age=25)
|
||||
user.age = "invalid" # ValidationError 발생
|
||||
```
|
||||
|
||||
### Extra 필드 처리
|
||||
|
||||
| 옵션 | 타입 | 기본값 | 설명 |
|
||||
|------|------|--------|------|
|
||||
| `extra` | `'allow' \| 'ignore' \| 'forbid'` | `'ignore'` | 추가 필드 처리 방식 |
|
||||
|
||||
**값 설명:**
|
||||
- `'ignore'`: 추가 필드 무시 (기본값)
|
||||
- `'allow'`: 추가 필드 허용, `__pydantic_extra__`에 저장
|
||||
- `'forbid'`: 추가 필드 입력 시 에러 발생
|
||||
|
||||
**예시:**
|
||||
```python
|
||||
class AllowExtra(BaseModel):
|
||||
model_config = ConfigDict(extra='allow')
|
||||
|
||||
name: str
|
||||
|
||||
data = AllowExtra(name="John", unknown_field="value")
|
||||
print(data.__pydantic_extra__) # {'unknown_field': 'value'}
|
||||
|
||||
class ForbidExtra(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
|
||||
name: str
|
||||
|
||||
ForbidExtra(name="John", unknown="value") # ValidationError 발생
|
||||
```
|
||||
|
||||
### 불변성 (Immutability)
|
||||
|
||||
| 옵션 | 타입 | 기본값 | 설명 |
|
||||
|------|------|--------|------|
|
||||
| `frozen` | `bool` | `False` | 모델을 불변(immutable)으로 만듦, `__hash__()` 구현 |
|
||||
|
||||
**예시:**
|
||||
```python
|
||||
class ImmutableUser(BaseModel):
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
name: str
|
||||
age: int
|
||||
|
||||
user = ImmutableUser(name="John", age=30)
|
||||
user.age = 31 # 에러 발생: Instance is frozen
|
||||
|
||||
# frozen=True이면 해시 가능
|
||||
users_set = {user} # 정상 작동
|
||||
```
|
||||
|
||||
### 별칭 (Alias) 설정
|
||||
|
||||
| 옵션 | 타입 | 기본값 | 설명 |
|
||||
|------|------|--------|------|
|
||||
| `populate_by_name` | `bool` | `False` | 필드명과 별칭 모두로 값 설정 허용 (deprecated) |
|
||||
| `validate_by_alias` | `bool` | `True` | 별칭으로 필드 값 설정 허용 |
|
||||
| `validate_by_name` | `bool` | `False` | 별칭이 있어도 필드명으로 값 설정 허용 |
|
||||
| `serialize_by_alias` | `bool` | `False` | 직렬화 시 별칭 사용 |
|
||||
| `alias_generator` | `Callable[[str], str] \| None` | `None` | 별칭 자동 생성 함수 |
|
||||
| `loc_by_alias` | `bool` | `True` | 에러 위치에 별칭 사용 |
|
||||
|
||||
**예시:**
|
||||
```python
|
||||
from pydantic import Field
|
||||
|
||||
class APIResponse(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
validate_by_alias=True,
|
||||
validate_by_name=True,
|
||||
serialize_by_alias=True
|
||||
)
|
||||
|
||||
user_name: str = Field(alias="userName")
|
||||
|
||||
# 둘 다 가능
|
||||
response1 = APIResponse(userName="John")
|
||||
response2 = APIResponse(user_name="John")
|
||||
|
||||
print(response1.model_dump(by_alias=True)) # {"userName": "John"}
|
||||
```
|
||||
|
||||
**예시 - alias_generator:**
|
||||
```python
|
||||
def to_camel(name: str) -> str:
|
||||
parts = name.split('_')
|
||||
return parts[0] + ''.join(word.capitalize() for word in parts[1:])
|
||||
|
||||
class CamelModel(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
alias_generator=to_camel,
|
||||
serialize_by_alias=True
|
||||
)
|
||||
|
||||
first_name: str
|
||||
last_name: str
|
||||
|
||||
data = CamelModel(firstName="John", lastName="Doe")
|
||||
print(data.model_dump(by_alias=True))
|
||||
# {"firstName": "John", "lastName": "Doe"}
|
||||
```
|
||||
|
||||
### JSON 스키마
|
||||
|
||||
| 옵션 | 타입 | 기본값 | 설명 |
|
||||
|------|------|--------|------|
|
||||
| `title` | `str \| None` | `None` | JSON 스키마 타이틀 |
|
||||
| `json_schema_extra` | `dict \| Callable \| None` | `None` | JSON 스키마에 추가할 정보 |
|
||||
| `json_schema_serialization_defaults_required` | `bool` | `False` | 직렬화 스키마에서 기본값이 있는 필드도 required로 표시 |
|
||||
| `json_schema_mode_override` | `Literal['validation', 'serialization', None]` | `None` | JSON 스키마 모드 강제 지정 |
|
||||
|
||||
**예시 - json_schema_extra:**
|
||||
```python
|
||||
class Product(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
title="상품 정보",
|
||||
json_schema_extra={
|
||||
"example": {
|
||||
"name": "노트북",
|
||||
"price": 1500000
|
||||
},
|
||||
"description": "상품 데이터를 나타내는 모델"
|
||||
}
|
||||
)
|
||||
|
||||
name: str
|
||||
price: int
|
||||
|
||||
# OpenAPI/Swagger 문서에 예시가 표시됨
|
||||
```
|
||||
|
||||
**예시 - Callable json_schema_extra:**
|
||||
```python
|
||||
def add_examples(schema: dict) -> dict:
|
||||
schema["examples"] = [
|
||||
{"name": "예시1", "value": 100},
|
||||
{"name": "예시2", "value": 200}
|
||||
]
|
||||
return schema
|
||||
|
||||
class DynamicSchema(BaseModel):
|
||||
model_config = ConfigDict(json_schema_extra=add_examples)
|
||||
|
||||
name: str
|
||||
value: int
|
||||
```
|
||||
|
||||
### ORM/속성 모드
|
||||
|
||||
| 옵션 | 타입 | 기본값 | 설명 |
|
||||
|------|------|--------|------|
|
||||
| `from_attributes` | `bool` | `False` | 객체 속성에서 모델 생성 허용 (SQLAlchemy 등) |
|
||||
|
||||
**예시:**
|
||||
```python
|
||||
class UserORM:
|
||||
def __init__(self, name: str, age: int):
|
||||
self.name = name
|
||||
self.age = age
|
||||
|
||||
class UserModel(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
name: str
|
||||
age: int
|
||||
|
||||
orm_user = UserORM(name="John", age=30)
|
||||
pydantic_user = UserModel.model_validate(orm_user)
|
||||
print(pydantic_user) # name='John' age=30
|
||||
```
|
||||
|
||||
### Enum 처리
|
||||
|
||||
| 옵션 | 타입 | 기본값 | 설명 |
|
||||
|------|------|--------|------|
|
||||
| `use_enum_values` | `bool` | `False` | Enum 대신 값(value)으로 저장 |
|
||||
|
||||
**예시:**
|
||||
```python
|
||||
from enum import Enum
|
||||
|
||||
class Status(Enum):
|
||||
ACTIVE = "active"
|
||||
INACTIVE = "inactive"
|
||||
|
||||
class User(BaseModel):
|
||||
model_config = ConfigDict(use_enum_values=True)
|
||||
|
||||
status: Status
|
||||
|
||||
user = User(status=Status.ACTIVE)
|
||||
print(user.status) # "active" (문자열)
|
||||
print(type(user.status)) # <class 'str'>
|
||||
|
||||
# use_enum_values=False (기본값)이면
|
||||
# user.status는 Status.ACTIVE (Enum 객체)
|
||||
```
|
||||
|
||||
### 직렬화 설정
|
||||
|
||||
| 옵션 | 타입 | 기본값 | 설명 |
|
||||
|------|------|--------|------|
|
||||
| `ser_json_timedelta` | `'iso8601' \| 'float'` | `'iso8601'` | timedelta JSON 직렬화 형식 |
|
||||
| `ser_json_bytes` | `'utf8' \| 'base64' \| 'hex'` | `'utf8'` | bytes JSON 직렬화 인코딩 |
|
||||
| `ser_json_inf_nan` | `'null' \| 'constants' \| 'strings'` | `'null'` | 무한대/NaN JSON 직렬화 형식 |
|
||||
|
||||
### 숫자/Float 설정
|
||||
|
||||
| 옵션 | 타입 | 기본값 | 설명 |
|
||||
|------|------|--------|------|
|
||||
| `allow_inf_nan` | `bool` | `True` | float에서 무한대/NaN 허용 |
|
||||
| `coerce_numbers_to_str` | `bool` | `False` | 숫자를 문자열로 강제 변환 허용 |
|
||||
|
||||
### 기타 설정
|
||||
|
||||
| 옵션 | 타입 | 기본값 | 설명 |
|
||||
|------|------|--------|------|
|
||||
| `protected_namespaces` | `tuple[str, ...]` | `('model_',)` | 보호할 필드명 접두사 |
|
||||
| `hide_input_in_errors` | `bool` | `False` | 에러 메시지에서 입력값 숨김 |
|
||||
| `defer_build` | `bool` | `False` | validator/serializer 빌드 지연 |
|
||||
| `use_attribute_docstrings` | `bool` | `False` | 속성 docstring을 필드 설명으로 사용 |
|
||||
| `regex_engine` | `'rust-regex' \| 'python-re'` | `'rust-regex'` | 정규식 엔진 선택 |
|
||||
| `validation_error_cause` | `bool` | `False` | Python 예외를 에러 원인에 포함 |
|
||||
|
||||
## 설정 상속
|
||||
|
||||
자식 모델은 부모 모델의 `model_config`를 상속받습니다.
|
||||
|
||||
```python
|
||||
class ParentModel(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
str_strip_whitespace=True,
|
||||
extra='allow'
|
||||
)
|
||||
|
||||
name: str
|
||||
|
||||
class ChildModel(ParentModel):
|
||||
model_config = ConfigDict(
|
||||
frozen=True # 부모 설정 + frozen=True
|
||||
)
|
||||
|
||||
age: int
|
||||
|
||||
# ChildModel은 str_strip_whitespace=True, extra='allow', frozen=True
|
||||
```
|
||||
|
||||
## FastAPI와 함께 사용
|
||||
|
||||
FastAPI에서 요청/응답 스키마로 사용할 때 특히 유용합니다.
|
||||
|
||||
```python
|
||||
from fastapi import FastAPI
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
class CreateUserRequest(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
str_strip_whitespace=True,
|
||||
json_schema_extra={
|
||||
"example": {
|
||||
"username": "johndoe",
|
||||
"email": "john@example.com"
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
username: str = Field(..., min_length=3, max_length=50)
|
||||
email: str
|
||||
|
||||
class UserResponse(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
from_attributes=True, # ORM 객체에서 변환 가능
|
||||
serialize_by_alias=True
|
||||
)
|
||||
|
||||
id: int
|
||||
user_name: str = Field(alias="userName")
|
||||
|
||||
@app.post("/users", response_model=UserResponse)
|
||||
async def create_user(user: CreateUserRequest):
|
||||
# user.username은 자동으로 공백이 제거됨
|
||||
...
|
||||
```
|
||||
|
||||
## 주의사항
|
||||
|
||||
1. **v1에서 마이그레이션**: `class Config`는 deprecated입니다. `model_config = ConfigDict(...)`를 사용하세요.
|
||||
|
||||
2. **populate_by_name은 deprecated**: `validate_by_alias`와 `validate_by_name`을 함께 사용하세요.
|
||||
|
||||
3. **json_encoders는 deprecated**: 커스텀 직렬화가 필요하면 `@field_serializer` 데코레이터를 사용하세요.
|
||||
|
||||
## 참고 자료
|
||||
|
||||
- [Pydantic Configuration API 공식 문서](https://docs.pydantic.dev/latest/api/config/)
|
||||
- [Pydantic Models 개념](https://docs.pydantic.dev/latest/concepts/models/)
|
||||
- [Pydantic Migration Guide](https://docs.pydantic.dev/latest/migration/)
|
||||
+2965
-2965
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+158
-158
@@ -1,158 +1,158 @@
|
||||
from app.core.database import Base
|
||||
from sqlalchemy import (
|
||||
Boolean,
|
||||
DateTime,
|
||||
Enum,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
PrimaryKeyConstraint,
|
||||
String,
|
||||
func,
|
||||
)
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
from starlette.authentication import BaseUser
|
||||
|
||||
|
||||
class User(Base, BaseUser):
|
||||
__tablename__ = "users"
|
||||
|
||||
id: Mapped[int] = mapped_column(
|
||||
Integer, primary_key=True, nullable=False, autoincrement=True
|
||||
)
|
||||
username: Mapped[str] = mapped_column(
|
||||
String(255), unique=True, nullable=False, index=True
|
||||
)
|
||||
email: Mapped[str] = mapped_column(
|
||||
String(255), unique=True, nullable=False, index=True
|
||||
)
|
||||
hashed_password: Mapped[str] = mapped_column(String(60), nullable=False)
|
||||
# age_level 컬럼을 Enum으로 정의
|
||||
age_level_choices = ["10", "20", "30", "40", "50", "60", "70", "80"]
|
||||
age_level: Mapped[str] = mapped_column(
|
||||
Enum(*age_level_choices, name="age_level_enum"),
|
||||
nullable=False,
|
||||
default="10",
|
||||
)
|
||||
is_active: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
created_at: Mapped[DateTime] = mapped_column(DateTime, server_default=func.now())
|
||||
|
||||
# One-to-many relationship with Post (DynamicMapped + lazy="dynamic")
|
||||
posts_user: Mapped[list["Post"]] = relationship("Post", back_populates="user_posts")
|
||||
|
||||
# # Many-to-many relationship with Group
|
||||
# user_groups: DynamicMapped["UserGroupAssociation"] = relationship(
|
||||
# "UserGroupAssociation", back_populates="user", lazy="dynamic"
|
||||
# )
|
||||
# n:m 관계 (Group) – 최적의 lazy 옵션: selectin
|
||||
group_user: Mapped[list["Group"]] = relationship(
|
||||
"Group",
|
||||
secondary="user_group_association",
|
||||
back_populates="user_group",
|
||||
lazy="selectin",
|
||||
)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"id={self.id}, username={self.username}"
|
||||
|
||||
@property
|
||||
def is_authenticated(self) -> bool:
|
||||
return self.is_active
|
||||
|
||||
@property
|
||||
def display_name(self) -> str:
|
||||
return self.username
|
||||
|
||||
@property
|
||||
def identity(self) -> str:
|
||||
return self.username
|
||||
|
||||
|
||||
# 1:N Relationship - Posts
|
||||
class Post(Base):
|
||||
__tablename__ = "posts"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
user_id: Mapped[int] = mapped_column(
|
||||
Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
title: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
content: Mapped[str] = mapped_column(String(10000), nullable=False)
|
||||
is_published: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
created_at: Mapped[DateTime] = mapped_column(DateTime, server_default=func.now())
|
||||
updated_at: Mapped[DateTime] = mapped_column(
|
||||
DateTime, server_default=func.now(), onupdate=func.now()
|
||||
)
|
||||
# tags: Mapped[dict] = mapped_column(MutableDict.as_mutable(JSONB), default=[]) // sqlite 지원 안함
|
||||
view_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
|
||||
# Many-to-one relationship with User (using dynamic loading)
|
||||
user_posts: Mapped["User"] = relationship("User", back_populates="posts_user")
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"Post(id={self.id}, user_id={self.user_id}, title={self.title})"
|
||||
|
||||
__table_args__ = (
|
||||
Index("idx_posts_user_id", "user_id"),
|
||||
Index("idx_posts_created_at", "created_at"),
|
||||
Index(
|
||||
"idx_posts_user_id_created_at", "user_id", "created_at"
|
||||
), # Composite index
|
||||
)
|
||||
|
||||
|
||||
# N:M Relationship - Users and Groups
|
||||
# Association table for many-to-many relationship
|
||||
# N:M Association Table (중간 테이블)
|
||||
class UserGroupAssociation(Base):
|
||||
__tablename__ = "user_group_association"
|
||||
|
||||
user_id: Mapped[int] = mapped_column(
|
||||
Integer, ForeignKey("users.id", ondelete="CASCADE"), primary_key=True
|
||||
)
|
||||
group_id: Mapped[int] = mapped_column(
|
||||
Integer, ForeignKey("groups.id", ondelete="CASCADE"), primary_key=True
|
||||
)
|
||||
|
||||
# # 관계 정의
|
||||
# user: Mapped["User"] = relationship("User", back_populates="user_groups")
|
||||
# group: Mapped["Group"] = relationship("Group", back_populates="group_users")
|
||||
# # 복합 기본 키 설정
|
||||
|
||||
# 기본 키 설정을 위한 __table_args__ 추가
|
||||
__table_args__ = (PrimaryKeyConstraint("user_id", "group_id"),)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"UserGroupAssociation(user_id={self.user_id}, group_id={self.group_id})"
|
||||
|
||||
|
||||
# Group 테이블
|
||||
class Group(Base):
|
||||
__tablename__ = "groups"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
name: Mapped[str] = mapped_column(String(255), nullable=False, unique=True)
|
||||
description: Mapped[str] = mapped_column(String(1000))
|
||||
is_public: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
created_at: Mapped[DateTime] = mapped_column(DateTime, server_default=func.now())
|
||||
updated_at: Mapped[DateTime] = mapped_column(
|
||||
DateTime, server_default=func.now(), onupdate=func.now()
|
||||
)
|
||||
|
||||
user_group: Mapped[list["User"]] = relationship(
|
||||
"User",
|
||||
secondary="user_group_association",
|
||||
back_populates="group_user",
|
||||
lazy="selectin",
|
||||
)
|
||||
|
||||
# Group을 만든 사용자와 관계 (일반적인 1:N 관계)
|
||||
def __repr__(self) -> str:
|
||||
return f"Group(id={self.id}, name={self.name})"
|
||||
|
||||
__table_args__ = (
|
||||
Index("idx_groups_name", "name"),
|
||||
Index("idx_groups_is_public", "is_public"),
|
||||
Index("idx_groups_created_at", "created_at"),
|
||||
Index("idx_groups_composite", "is_public", "created_at"),
|
||||
)
|
||||
from app.core.database import Base
|
||||
from sqlalchemy import (
|
||||
Boolean,
|
||||
DateTime,
|
||||
Enum,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
PrimaryKeyConstraint,
|
||||
String,
|
||||
func,
|
||||
)
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
from starlette.authentication import BaseUser
|
||||
|
||||
|
||||
class User(Base, BaseUser):
|
||||
__tablename__ = "users"
|
||||
|
||||
id: Mapped[int] = mapped_column(
|
||||
Integer, primary_key=True, nullable=False, autoincrement=True
|
||||
)
|
||||
username: Mapped[str] = mapped_column(
|
||||
String(255), unique=True, nullable=False, index=True
|
||||
)
|
||||
email: Mapped[str] = mapped_column(
|
||||
String(255), unique=True, nullable=False, index=True
|
||||
)
|
||||
hashed_password: Mapped[str] = mapped_column(String(60), nullable=False)
|
||||
# age_level 컬럼을 Enum으로 정의
|
||||
age_level_choices = ["10", "20", "30", "40", "50", "60", "70", "80"]
|
||||
age_level: Mapped[str] = mapped_column(
|
||||
Enum(*age_level_choices, name="age_level_enum"),
|
||||
nullable=False,
|
||||
default="10",
|
||||
)
|
||||
is_active: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
created_at: Mapped[DateTime] = mapped_column(DateTime, server_default=func.now())
|
||||
|
||||
# One-to-many relationship with Post (DynamicMapped + lazy="dynamic")
|
||||
posts_user: Mapped[list["Post"]] = relationship("Post", back_populates="user_posts")
|
||||
|
||||
# # Many-to-many relationship with Group
|
||||
# user_groups: DynamicMapped["UserGroupAssociation"] = relationship(
|
||||
# "UserGroupAssociation", back_populates="user", lazy="dynamic"
|
||||
# )
|
||||
# n:m 관계 (Group) – 최적의 lazy 옵션: selectin
|
||||
group_user: Mapped[list["Group"]] = relationship(
|
||||
"Group",
|
||||
secondary="user_group_association",
|
||||
back_populates="user_group",
|
||||
lazy="selectin",
|
||||
)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"id={self.id}, username={self.username}"
|
||||
|
||||
@property
|
||||
def is_authenticated(self) -> bool:
|
||||
return self.is_active
|
||||
|
||||
@property
|
||||
def display_name(self) -> str:
|
||||
return self.username
|
||||
|
||||
@property
|
||||
def identity(self) -> str:
|
||||
return self.username
|
||||
|
||||
|
||||
# 1:N Relationship - Posts
|
||||
class Post(Base):
|
||||
__tablename__ = "posts"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
user_id: Mapped[int] = mapped_column(
|
||||
Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
title: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
content: Mapped[str] = mapped_column(String(10000), nullable=False)
|
||||
is_published: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
created_at: Mapped[DateTime] = mapped_column(DateTime, server_default=func.now())
|
||||
updated_at: Mapped[DateTime] = mapped_column(
|
||||
DateTime, server_default=func.now(), onupdate=func.now()
|
||||
)
|
||||
# tags: Mapped[dict] = mapped_column(MutableDict.as_mutable(JSONB), default=[]) // sqlite 지원 안함
|
||||
view_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
|
||||
# Many-to-one relationship with User (using dynamic loading)
|
||||
user_posts: Mapped["User"] = relationship("User", back_populates="posts_user")
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"Post(id={self.id}, user_id={self.user_id}, title={self.title})"
|
||||
|
||||
__table_args__ = (
|
||||
Index("idx_posts_user_id", "user_id"),
|
||||
Index("idx_posts_created_at", "created_at"),
|
||||
Index(
|
||||
"idx_posts_user_id_created_at", "user_id", "created_at"
|
||||
), # Composite index
|
||||
)
|
||||
|
||||
|
||||
# N:M Relationship - Users and Groups
|
||||
# Association table for many-to-many relationship
|
||||
# N:M Association Table (중간 테이블)
|
||||
class UserGroupAssociation(Base):
|
||||
__tablename__ = "user_group_association"
|
||||
|
||||
user_id: Mapped[int] = mapped_column(
|
||||
Integer, ForeignKey("users.id", ondelete="CASCADE"), primary_key=True
|
||||
)
|
||||
group_id: Mapped[int] = mapped_column(
|
||||
Integer, ForeignKey("groups.id", ondelete="CASCADE"), primary_key=True
|
||||
)
|
||||
|
||||
# # 관계 정의
|
||||
# user: Mapped["User"] = relationship("User", back_populates="user_groups")
|
||||
# group: Mapped["Group"] = relationship("Group", back_populates="group_users")
|
||||
# # 복합 기본 키 설정
|
||||
|
||||
# 기본 키 설정을 위한 __table_args__ 추가
|
||||
__table_args__ = (PrimaryKeyConstraint("user_id", "group_id"),)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"UserGroupAssociation(user_id={self.user_id}, group_id={self.group_id})"
|
||||
|
||||
|
||||
# Group 테이블
|
||||
class Group(Base):
|
||||
__tablename__ = "groups"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
name: Mapped[str] = mapped_column(String(255), nullable=False, unique=True)
|
||||
description: Mapped[str] = mapped_column(String(1000))
|
||||
is_public: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
created_at: Mapped[DateTime] = mapped_column(DateTime, server_default=func.now())
|
||||
updated_at: Mapped[DateTime] = mapped_column(
|
||||
DateTime, server_default=func.now(), onupdate=func.now()
|
||||
)
|
||||
|
||||
user_group: Mapped[list["User"]] = relationship(
|
||||
"User",
|
||||
secondary="user_group_association",
|
||||
back_populates="group_user",
|
||||
lazy="selectin",
|
||||
)
|
||||
|
||||
# Group을 만든 사용자와 관계 (일반적인 1:N 관계)
|
||||
def __repr__(self) -> str:
|
||||
return f"Group(id={self.id}, name={self.name})"
|
||||
|
||||
__table_args__ = (
|
||||
Index("idx_groups_name", "name"),
|
||||
Index("idx_groups_is_public", "is_public"),
|
||||
Index("idx_groups_created_at", "created_at"),
|
||||
Index("idx_groups_composite", "is_public", "created_at"),
|
||||
)
|
||||
Reference in new issue
Block a user