세션 및 비동기 처리 개선
This commit is contained in:
1 parent
153b9f0ca4
commit
5c99610e00
10 files changed
+4559
-289
No files matched your search
+112
-26
@@ -22,9 +22,15 @@ template = await creatomate.get_one_template_data(template_id)
|
||||
# 영상 렌더링 요청 (비동기)
|
||||
response = await creatomate.make_creatomate_call(template_id, modifications)
|
||||
```
|
||||
|
||||
## 성능 최적화
|
||||
- 템플릿 캐싱: 템플릿 데이터는 메모리에 캐싱되어 반복 조회 시 API 호출을 줄입니다.
|
||||
- HTTP 클라이언트 재사용: 모듈 레벨의 공유 클라이언트로 커넥션 풀을 재사용합니다.
|
||||
- 캐시 만료: 기본 5분 후 자동 만료 (CACHE_TTL_SECONDS로 조정 가능)
|
||||
"""
|
||||
|
||||
import copy
|
||||
import time
|
||||
from typing import Literal
|
||||
|
||||
import httpx
|
||||
@@ -35,6 +41,51 @@ from config import apikey_settings, creatomate_settings
|
||||
# Orientation 타입 정의
|
||||
OrientationType = Literal["horizontal", "vertical"]
|
||||
|
||||
# =============================================================================
|
||||
# 모듈 레벨 캐시 및 HTTP 클라이언트 (싱글톤 패턴)
|
||||
# =============================================================================
|
||||
|
||||
# 템플릿 캐시: {template_id: {"data": dict, "cached_at": float}}
|
||||
_template_cache: dict[str, dict] = {}
|
||||
|
||||
# 캐시 TTL (초) - 기본 5분
|
||||
CACHE_TTL_SECONDS = 300
|
||||
|
||||
# 모듈 레벨 공유 HTTP 클라이언트 (커넥션 풀 재사용)
|
||||
_shared_client: httpx.AsyncClient | None = None
|
||||
|
||||
|
||||
async def get_shared_client() -> httpx.AsyncClient:
|
||||
"""공유 HTTP 클라이언트를 반환합니다. 없으면 생성합니다."""
|
||||
global _shared_client
|
||||
if _shared_client is None or _shared_client.is_closed:
|
||||
_shared_client = httpx.AsyncClient(
|
||||
timeout=httpx.Timeout(60.0, connect=10.0),
|
||||
limits=httpx.Limits(max_keepalive_connections=10, max_connections=20),
|
||||
)
|
||||
return _shared_client
|
||||
|
||||
|
||||
async def close_shared_client() -> None:
|
||||
"""공유 HTTP 클라이언트를 닫습니다. 앱 종료 시 호출하세요."""
|
||||
global _shared_client
|
||||
if _shared_client is not None and not _shared_client.is_closed:
|
||||
await _shared_client.aclose()
|
||||
_shared_client = None
|
||||
print("[CreatomateService] Shared HTTP client closed")
|
||||
|
||||
|
||||
def clear_template_cache() -> None:
|
||||
"""템플릿 캐시를 전체 삭제합니다."""
|
||||
global _template_cache
|
||||
_template_cache.clear()
|
||||
print("[CreatomateService] Template cache cleared")
|
||||
|
||||
|
||||
def _is_cache_valid(cached_at: float) -> bool:
|
||||
"""캐시가 유효한지 확인합니다."""
|
||||
return (time.time() - cached_at) < CACHE_TTL_SECONDS
|
||||
|
||||
|
||||
class CreatomateService:
|
||||
"""Creatomate API를 통한 영상 생성 서비스
|
||||
@@ -90,18 +141,53 @@ class CreatomateService:
|
||||
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()
|
||||
client = await get_shared_client()
|
||||
response = await client.get(url, headers=self.headers, timeout=30.0)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
async def get_one_template_data(self, template_id: str) -> dict:
|
||||
"""특정 템플릿 ID로 템플릿 정보를 조회합니다."""
|
||||
async def get_one_template_data(
|
||||
self,
|
||||
template_id: str,
|
||||
use_cache: bool = True,
|
||||
) -> dict:
|
||||
"""특정 템플릿 ID로 템플릿 정보를 조회합니다.
|
||||
|
||||
Args:
|
||||
template_id: 조회할 템플릿 ID
|
||||
use_cache: 캐시 사용 여부 (기본: True)
|
||||
|
||||
Returns:
|
||||
템플릿 데이터 (deep copy)
|
||||
"""
|
||||
global _template_cache
|
||||
|
||||
# 캐시 확인
|
||||
if use_cache and template_id in _template_cache:
|
||||
cached = _template_cache[template_id]
|
||||
if _is_cache_valid(cached["cached_at"]):
|
||||
print(f"[CreatomateService] Cache HIT - {template_id}")
|
||||
return copy.deepcopy(cached["data"])
|
||||
else:
|
||||
# 만료된 캐시 삭제
|
||||
del _template_cache[template_id]
|
||||
print(f"[CreatomateService] Cache EXPIRED - {template_id}")
|
||||
|
||||
# API 호출
|
||||
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()
|
||||
return response.json()
|
||||
client = await get_shared_client()
|
||||
response = await client.get(url, headers=self.headers, timeout=30.0)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
|
||||
# 캐시 저장
|
||||
_template_cache[template_id] = {
|
||||
"data": data,
|
||||
"cached_at": time.time(),
|
||||
}
|
||||
print(f"[CreatomateService] Cache MISS - {template_id} (cached)")
|
||||
|
||||
return copy.deepcopy(data)
|
||||
|
||||
# 하위 호환성을 위한 별칭 (deprecated)
|
||||
async def get_one_template_data_async(self, template_id: str) -> dict:
|
||||
@@ -245,12 +331,12 @@ class CreatomateService:
|
||||
"template_id": template_id,
|
||||
"modifications": modifications,
|
||||
}
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.post(
|
||||
url, json=data, headers=self.headers, timeout=60.0
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
client = await get_shared_client()
|
||||
response = await client.post(
|
||||
url, json=data, headers=self.headers, timeout=60.0
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
async def make_creatomate_custom_call(self, source: dict) -> dict:
|
||||
"""템플릿 없이 Creatomate에 커스텀 렌더링 요청을 보냅니다.
|
||||
@@ -259,12 +345,12 @@ class CreatomateService:
|
||||
response에 요청 정보가 있으니 폴링 필요
|
||||
"""
|
||||
url = f"{self.BASE_URL}/v2/renders"
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.post(
|
||||
url, json=source, headers=self.headers, timeout=60.0
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
client = await get_shared_client()
|
||||
response = await client.post(
|
||||
url, json=source, headers=self.headers, timeout=60.0
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
# 하위 호환성을 위한 별칭 (deprecated)
|
||||
async def make_creatomate_custom_call_async(self, source: dict) -> dict:
|
||||
@@ -293,10 +379,10 @@ class CreatomateService:
|
||||
- failed: 실패
|
||||
"""
|
||||
url = f"{self.BASE_URL}/v1/renders/{render_id}"
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.get(url, headers=self.headers, timeout=30.0)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
client = await get_shared_client()
|
||||
response = await client.get(url, headers=self.headers, timeout=30.0)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
# 하위 호환성을 위한 별칭 (deprecated)
|
||||
async def get_render_status_async(self, render_id: str) -> dict:
|
||||
|
||||
Reference in new issue
Block a user