세션 및 비동기 처리 개선
This commit is contained in:
1 parent
153b9f0ca4
commit
5c99610e00
10 files changed
+4559
-289
No files matched your search
+48
-70
@@ -1,9 +1,7 @@
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import AsyncGenerator
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
from sqlalchemy.pool import NullPool
|
||||
|
||||
from config import db_settings
|
||||
|
||||
@@ -12,24 +10,25 @@ class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
# 데이터베이스 엔진 생성
|
||||
# =============================================================================
|
||||
# 메인 엔진 (FastAPI 요청용)
|
||||
# =============================================================================
|
||||
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",
|
||||
pool_size=20, # 기본 풀 크기: 20
|
||||
max_overflow=20, # 추가 연결: 20 (총 최대 40)
|
||||
pool_timeout=30, # 풀에서 연결 대기 시간 (초)
|
||||
pool_recycle=3600, # 1시간마다 연결 재생성
|
||||
pool_pre_ping=True, # 연결 유효성 검사
|
||||
pool_reset_on_return="rollback", # 반환 시 롤백으로 초기화
|
||||
connect_args={
|
||||
"connect_timeout": 3,
|
||||
"connect_timeout": 10, # DB 연결 타임아웃
|
||||
"charset": "utf8mb4",
|
||||
# "allow_public_key_retrieval": True,
|
||||
},
|
||||
)
|
||||
|
||||
# Async sessionmaker 생성
|
||||
# 메인 세션 팩토리 (FastAPI DI용)
|
||||
AsyncSessionLocal = async_sessionmaker(
|
||||
bind=engine,
|
||||
class_=AsyncSession,
|
||||
@@ -38,6 +37,33 @@ AsyncSessionLocal = async_sessionmaker(
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# 백그라운드 태스크 전용 엔진 (메인 풀과 분리)
|
||||
# =============================================================================
|
||||
background_engine = create_async_engine(
|
||||
url=db_settings.MYSQL_URL,
|
||||
echo=False,
|
||||
pool_size=10, # 백그라운드용 풀 크기: 10
|
||||
max_overflow=10, # 추가 연결: 10 (총 최대 20)
|
||||
pool_timeout=60, # 백그라운드는 대기 시간 여유있게
|
||||
pool_recycle=3600,
|
||||
pool_pre_ping=True,
|
||||
pool_reset_on_return="rollback",
|
||||
connect_args={
|
||||
"connect_timeout": 10,
|
||||
"charset": "utf8mb4",
|
||||
},
|
||||
)
|
||||
|
||||
# 백그라운드 세션 팩토리
|
||||
BackgroundSessionLocal = async_sessionmaker(
|
||||
bind=background_engine,
|
||||
class_=AsyncSession,
|
||||
expire_on_commit=False,
|
||||
autoflush=False,
|
||||
)
|
||||
|
||||
|
||||
async def create_db_tables():
|
||||
import asyncio
|
||||
|
||||
@@ -56,72 +82,24 @@ async def create_db_tables():
|
||||
|
||||
# FastAPI 의존성용 세션 제너레이터
|
||||
async def get_session() -> AsyncGenerator[AsyncSession, None]:
|
||||
# 커넥션 풀 상태 로깅 (디버깅용)
|
||||
pool = engine.pool
|
||||
print(f"[get_session] Pool status - size: {pool.size()}, checked_in: {pool.checkedin()}, checked_out: {pool.checkedout()}, overflow: {pool.overflow()}")
|
||||
|
||||
async with AsyncSessionLocal() as session:
|
||||
try:
|
||||
yield session
|
||||
# print("Session commited")
|
||||
# await session.commit()
|
||||
except Exception as e:
|
||||
await session.rollback()
|
||||
print(f"Session rollback due to: {e}")
|
||||
print(f"[get_session] Session rollback due to: {e}")
|
||||
raise e
|
||||
# async with 종료 시 session.close()가 자동 호출됨
|
||||
finally:
|
||||
# 명시적으로 세션 종료 확인
|
||||
print(f"[get_session] Session closing - Pool checked_out: {pool.checkedout()}")
|
||||
|
||||
|
||||
# 앱 종료 시 엔진 리소스 정리 함수
|
||||
async def dispose_engine() -> None:
|
||||
await engine.dispose()
|
||||
print("Database engine disposed")
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# 백그라운드 태스크용 세션 (별도 이벤트 루프에서 사용)
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def get_worker_session() -> AsyncGenerator[AsyncSession, None]:
|
||||
"""백그라운드 태스크용 세션 컨텍스트 매니저
|
||||
|
||||
asyncio.run()으로 새 이벤트 루프를 생성하는 백그라운드 태스크에서 사용합니다.
|
||||
NullPool을 사용하여 연결 풀링을 비활성화하고, 이벤트 루프 충돌을 방지합니다.
|
||||
|
||||
get_session()과의 차이점:
|
||||
- get_session(): FastAPI DI용, 메인 이벤트 루프의 연결 풀 사용
|
||||
- get_worker_session(): 백그라운드 태스크용, NullPool로 매번 새 연결 생성
|
||||
|
||||
Usage:
|
||||
async with get_worker_session() as session:
|
||||
result = await session.execute(select(Model))
|
||||
await session.commit()
|
||||
|
||||
Note:
|
||||
- 매 호출마다 엔진을 생성하고 dispose하므로 오버헤드가 있음
|
||||
- 빈번한 호출이 필요한 경우 방법 1(모듈 레벨 엔진)을 고려
|
||||
"""
|
||||
worker_engine = create_async_engine(
|
||||
url=db_settings.MYSQL_URL,
|
||||
poolclass=NullPool,
|
||||
connect_args={
|
||||
"connect_timeout": 3,
|
||||
"charset": "utf8mb4",
|
||||
},
|
||||
)
|
||||
session_factory = async_sessionmaker(
|
||||
bind=worker_engine,
|
||||
class_=AsyncSession,
|
||||
expire_on_commit=False,
|
||||
autoflush=False,
|
||||
)
|
||||
|
||||
async with session_factory() as session:
|
||||
try:
|
||||
yield session
|
||||
except Exception as e:
|
||||
await session.rollback()
|
||||
print(f"Worker session rollback due to: {e}")
|
||||
raise e
|
||||
finally:
|
||||
await session.close()
|
||||
|
||||
await worker_engine.dispose()
|
||||
await background_engine.dispose()
|
||||
print("Database engines disposed (main + background)")
|
||||
@@ -8,7 +8,7 @@ import aiofiles
|
||||
from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile, status
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database.session import get_session
|
||||
from app.database.session import get_session, AsyncSessionLocal
|
||||
from app.home.models import Image
|
||||
from app.home.schemas.home_schema import (
|
||||
CrawlingRequest,
|
||||
@@ -497,13 +497,19 @@ async def upload_images_blob(
|
||||
files: Optional[list[UploadFile]] = File(
|
||||
default=None, description="이미지 바이너리 파일 목록"
|
||||
),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> ImageUploadResponse:
|
||||
"""이미지 업로드 (URL + Azure Blob Storage)"""
|
||||
"""이미지 업로드 (URL + Azure Blob Storage)
|
||||
|
||||
3단계로 분리하여 세션 점유 시간 최소화:
|
||||
- Stage 1: 입력 검증 및 파일 데이터 준비 (세션 없음)
|
||||
- Stage 2: Azure Blob 업로드 (세션 없음)
|
||||
- Stage 3: DB 저장 (새 세션으로 빠르게 처리)
|
||||
"""
|
||||
# task_id 생성
|
||||
task_id = await generate_task_id()
|
||||
print(f"[upload_images_blob] START - task_id: {task_id}")
|
||||
|
||||
# 1. 진입 검증
|
||||
# ========== Stage 1: 입력 검증 및 파일 데이터 준비 (세션 없음) ==========
|
||||
has_images_json = images_json is not None and images_json.strip() != ""
|
||||
has_files = files is not None and len(files) > 0
|
||||
|
||||
@@ -513,9 +519,9 @@ async def upload_images_blob(
|
||||
detail="images_json 또는 files 중 하나는 반드시 제공해야 합니다.",
|
||||
)
|
||||
|
||||
# 2. images_json 파싱
|
||||
# images_json 파싱
|
||||
url_images: list[ImageUrlItem] = []
|
||||
if has_images_json:
|
||||
if has_images_json and images_json:
|
||||
try:
|
||||
parsed = json.loads(images_json)
|
||||
if isinstance(parsed, list):
|
||||
@@ -526,8 +532,8 @@ async def upload_images_blob(
|
||||
detail=f"images_json 파싱 오류: {str(e)}",
|
||||
)
|
||||
|
||||
# 3. 유효한 파일만 필터링
|
||||
valid_files: list[UploadFile] = []
|
||||
# 유효한 파일만 필터링 및 파일 내용 미리 읽기
|
||||
valid_files_data: list[tuple[str, str, bytes]] = [] # (original_name, ext, content)
|
||||
skipped_files: list[str] = []
|
||||
if has_files and files:
|
||||
for f in files:
|
||||
@@ -536,50 +542,36 @@ async def upload_images_blob(
|
||||
is_real_file = f.filename and f.filename != "filename"
|
||||
|
||||
if f and is_real_file and is_valid_ext and is_not_empty:
|
||||
valid_files.append(f)
|
||||
# 파일 내용을 미리 읽어둠
|
||||
content = await f.read()
|
||||
ext = _get_file_extension(f.filename) # type: ignore[arg-type]
|
||||
valid_files_data.append((f.filename or "image", ext, content))
|
||||
else:
|
||||
skipped_files.append(f.filename or "unknown")
|
||||
|
||||
if not url_images and not valid_files:
|
||||
if not url_images and not valid_files_data:
|
||||
detail = (
|
||||
f"유효한 이미지가 없습니다. "
|
||||
f"지원 확장자: {', '.join(ALLOWED_IMAGE_EXTENSIONS)}. "
|
||||
f"건너뛴 파일: {skipped_files}"
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"유효한 이미지가 없습니다. 지원 확장자: {', '.join(ALLOWED_IMAGE_EXTENSIONS)}. 건너뛴 파일: {skipped_files}",
|
||||
detail=detail,
|
||||
)
|
||||
|
||||
result_images: list[ImageUploadResultItem] = []
|
||||
img_order = 0
|
||||
print(f"[upload_images_blob] Stage 1 done - urls: {len(url_images)}, "
|
||||
f"files: {len(valid_files_data)}")
|
||||
|
||||
# 1. URL 이미지 저장
|
||||
for url_item in url_images:
|
||||
img_name = url_item.name or _extract_image_name(url_item.url, img_order)
|
||||
# ========== Stage 2: Azure Blob 업로드 (세션 없음) ==========
|
||||
# 업로드 결과를 저장할 리스트 (나중에 DB에 저장)
|
||||
blob_upload_results: list[tuple[str, str]] = [] # (img_name, blob_url)
|
||||
img_order = len(url_images) # URL 이미지 다음 순서부터 시작
|
||||
|
||||
image = Image(
|
||||
task_id=task_id,
|
||||
img_name=img_name,
|
||||
img_url=url_item.url,
|
||||
img_order=img_order,
|
||||
)
|
||||
session.add(image)
|
||||
await session.flush()
|
||||
|
||||
result_images.append(
|
||||
ImageUploadResultItem(
|
||||
id=image.id,
|
||||
img_name=img_name,
|
||||
img_url=url_item.url,
|
||||
img_order=img_order,
|
||||
source="url",
|
||||
)
|
||||
)
|
||||
img_order += 1
|
||||
|
||||
# 2. 바이너리 파일을 Azure Blob Storage에 직접 업로드 (media 저장 없음)
|
||||
if valid_files:
|
||||
if valid_files_data:
|
||||
uploader = AzureBlobUploader(task_id=task_id)
|
||||
|
||||
for file in valid_files:
|
||||
original_name = file.filename or "image"
|
||||
ext = _get_file_extension(file.filename) # type: ignore[arg-type]
|
||||
for original_name, ext, file_content in valid_files_data:
|
||||
name_without_ext = (
|
||||
original_name.rsplit(".", 1)[0]
|
||||
if "." in original_name
|
||||
@@ -587,49 +579,83 @@ async def upload_images_blob(
|
||||
)
|
||||
filename = f"{name_without_ext}_{img_order:03d}{ext}"
|
||||
|
||||
# 파일 내용 읽기
|
||||
file_content = await file.read()
|
||||
|
||||
# Azure Blob Storage에 직접 업로드
|
||||
upload_success = await uploader.upload_image_bytes(file_content, filename)
|
||||
|
||||
if upload_success:
|
||||
blob_url = uploader.public_url
|
||||
img_name = file.filename or filename
|
||||
|
||||
image = Image(
|
||||
task_id=task_id,
|
||||
img_name=img_name,
|
||||
img_url=blob_url,
|
||||
img_order=img_order,
|
||||
)
|
||||
session.add(image)
|
||||
await session.flush()
|
||||
|
||||
result_images.append(
|
||||
ImageUploadResultItem(
|
||||
id=image.id,
|
||||
img_name=img_name,
|
||||
img_url=blob_url,
|
||||
img_order=img_order,
|
||||
source="blob",
|
||||
)
|
||||
)
|
||||
blob_upload_results.append((original_name, blob_url))
|
||||
img_order += 1
|
||||
else:
|
||||
skipped_files.append(filename)
|
||||
|
||||
saved_count = len(result_images)
|
||||
await session.commit()
|
||||
print(f"[upload_images_blob] Stage 2 done - blob uploads: "
|
||||
f"{len(blob_upload_results)}, skipped: {len(skipped_files)}")
|
||||
|
||||
# Image 테이블에서 현재 task_id의 이미지 URL 목록 조회
|
||||
# ========== Stage 3: DB 저장 (새 세션으로 빠르게 처리) ==========
|
||||
result_images: list[ImageUploadResultItem] = []
|
||||
img_order = 0
|
||||
|
||||
async with AsyncSessionLocal() as session:
|
||||
# URL 이미지 저장
|
||||
for url_item in url_images:
|
||||
img_name = url_item.name or _extract_image_name(url_item.url, img_order)
|
||||
|
||||
image = Image(
|
||||
task_id=task_id,
|
||||
img_name=img_name,
|
||||
img_url=url_item.url,
|
||||
img_order=img_order,
|
||||
)
|
||||
session.add(image)
|
||||
await session.flush()
|
||||
|
||||
result_images.append(
|
||||
ImageUploadResultItem(
|
||||
id=image.id,
|
||||
img_name=img_name,
|
||||
img_url=url_item.url,
|
||||
img_order=img_order,
|
||||
source="url",
|
||||
)
|
||||
)
|
||||
img_order += 1
|
||||
|
||||
# Blob 업로드 결과 저장
|
||||
for img_name, blob_url in blob_upload_results:
|
||||
image = Image(
|
||||
task_id=task_id,
|
||||
img_name=img_name,
|
||||
img_url=blob_url,
|
||||
img_order=img_order,
|
||||
)
|
||||
session.add(image)
|
||||
await session.flush()
|
||||
|
||||
result_images.append(
|
||||
ImageUploadResultItem(
|
||||
id=image.id,
|
||||
img_name=img_name,
|
||||
img_url=blob_url,
|
||||
img_order=img_order,
|
||||
source="blob",
|
||||
)
|
||||
)
|
||||
img_order += 1
|
||||
|
||||
await session.commit()
|
||||
|
||||
saved_count = len(result_images)
|
||||
image_urls = [img.img_url for img in result_images]
|
||||
|
||||
print(f"[upload_images_blob] SUCCESS - task_id: {task_id}, "
|
||||
f"total: {saved_count}, returning response...")
|
||||
|
||||
return ImageUploadResponse(
|
||||
task_id=task_id,
|
||||
total_count=len(result_images),
|
||||
url_count=len(url_images),
|
||||
file_count=len(valid_files) - len(skipped_files),
|
||||
file_count=len(blob_upload_results),
|
||||
saved_count=saved_count,
|
||||
images=result_images,
|
||||
image_urls=image_urls,
|
||||
|
||||
@@ -6,7 +6,7 @@ Lyric Background Tasks
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.database.session import AsyncSessionLocal
|
||||
from app.database.session import BackgroundSessionLocal
|
||||
from app.lyric.models import Lyric
|
||||
from app.utils.chatgpt_prompt import ChatgptService
|
||||
|
||||
@@ -55,8 +55,8 @@ async def generate_lyric_background(
|
||||
pattern.lower() in result.lower() for pattern in failure_patterns
|
||||
)
|
||||
|
||||
# Lyric 테이블 업데이트 (새 세션 사용)
|
||||
async with AsyncSessionLocal() as session:
|
||||
# Lyric 테이블 업데이트 (백그라운드 전용 세션 사용)
|
||||
async with BackgroundSessionLocal() as session:
|
||||
query_result = await session.execute(
|
||||
select(Lyric)
|
||||
.where(Lyric.task_id == task_id)
|
||||
@@ -82,7 +82,7 @@ async def generate_lyric_background(
|
||||
except Exception as e:
|
||||
print(f"[generate_lyric_background] EXCEPTION - task_id: {task_id}, error: {e}")
|
||||
# 실패 시 Lyric 테이블 업데이트
|
||||
async with AsyncSessionLocal() as session:
|
||||
async with BackgroundSessionLocal() as session:
|
||||
query_result = await session.execute(
|
||||
select(Lyric)
|
||||
.where(Lyric.task_id == task_id)
|
||||
|
||||
@@ -11,7 +11,7 @@ import aiofiles
|
||||
import httpx
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.database.session import AsyncSessionLocal
|
||||
from app.database.session import BackgroundSessionLocal
|
||||
from app.song.models import Song
|
||||
from app.utils.common import generate_task_id
|
||||
from app.utils.upload_blob_as_request import AzureBlobUploader
|
||||
@@ -65,7 +65,7 @@ async def download_and_save_song(
|
||||
print(f"[download_and_save_song] URL generated - task_id: {task_id}, url: {file_url}")
|
||||
|
||||
# Song 테이블 업데이트 (새 세션 사용)
|
||||
async with AsyncSessionLocal() as session:
|
||||
async with BackgroundSessionLocal() as session:
|
||||
# 여러 개 있을 경우 가장 최근 것 선택
|
||||
result = await session.execute(
|
||||
select(Song)
|
||||
@@ -86,7 +86,7 @@ async def download_and_save_song(
|
||||
except Exception as e:
|
||||
print(f"[download_and_save_song] EXCEPTION - task_id: {task_id}, error: {e}")
|
||||
# 실패 시 Song 테이블 업데이트
|
||||
async with AsyncSessionLocal() as session:
|
||||
async with BackgroundSessionLocal() as session:
|
||||
# 여러 개 있을 경우 가장 최근 것 선택
|
||||
result = await session.execute(
|
||||
select(Song)
|
||||
@@ -153,7 +153,7 @@ async def download_and_upload_song_to_blob(
|
||||
print(f"[download_and_upload_song_to_blob] Uploaded to Blob - task_id: {task_id}, url: {blob_url}")
|
||||
|
||||
# Song 테이블 업데이트 (새 세션 사용)
|
||||
async with AsyncSessionLocal() as session:
|
||||
async with BackgroundSessionLocal() as session:
|
||||
# 여러 개 있을 경우 가장 최근 것 선택
|
||||
result = await session.execute(
|
||||
select(Song)
|
||||
@@ -174,7 +174,7 @@ async def download_and_upload_song_to_blob(
|
||||
except Exception as e:
|
||||
print(f"[download_and_upload_song_to_blob] EXCEPTION - task_id: {task_id}, error: {e}")
|
||||
# 실패 시 Song 테이블 업데이트
|
||||
async with AsyncSessionLocal() as session:
|
||||
async with BackgroundSessionLocal() as session:
|
||||
result = await session.execute(
|
||||
select(Song)
|
||||
.where(Song.task_id == task_id)
|
||||
@@ -226,7 +226,7 @@ async def download_and_upload_song_by_suno_task_id(
|
||||
|
||||
try:
|
||||
# suno_task_id로 Song 조회하여 task_id 가져오기
|
||||
async with AsyncSessionLocal() as session:
|
||||
async with BackgroundSessionLocal() as session:
|
||||
result = await session.execute(
|
||||
select(Song)
|
||||
.where(Song.suno_task_id == suno_task_id)
|
||||
@@ -277,7 +277,7 @@ async def download_and_upload_song_by_suno_task_id(
|
||||
print(f"[download_and_upload_song_by_suno_task_id] Uploaded to Blob - suno_task_id: {suno_task_id}, url: {blob_url}")
|
||||
|
||||
# Song 테이블 업데이트 (새 세션 사용)
|
||||
async with AsyncSessionLocal() as session:
|
||||
async with BackgroundSessionLocal() as session:
|
||||
result = await session.execute(
|
||||
select(Song)
|
||||
.where(Song.suno_task_id == suno_task_id)
|
||||
@@ -300,7 +300,7 @@ async def download_and_upload_song_by_suno_task_id(
|
||||
print(f"[download_and_upload_song_by_suno_task_id] EXCEPTION - suno_task_id: {suno_task_id}, error: {e}")
|
||||
# 실패 시 Song 테이블 업데이트
|
||||
if task_id:
|
||||
async with AsyncSessionLocal() as session:
|
||||
async with BackgroundSessionLocal() as session:
|
||||
result = await session.execute(
|
||||
select(Song)
|
||||
.where(Song.suno_task_id == suno_task_id)
|
||||
|
||||
+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:
|
||||
|
||||
+174
-107
@@ -96,133 +96,173 @@ async def generate_video(
|
||||
default="vertical",
|
||||
description="영상 방향 (horizontal: 가로형, vertical: 세로형)",
|
||||
),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> GenerateVideoResponse:
|
||||
"""Creatomate API를 통해 영상을 생성합니다.
|
||||
|
||||
1. task_id로 Project, Lyric, Song, Image 조회
|
||||
1. task_id로 Project, Lyric, Song, Image 병렬 조회
|
||||
2. Video 테이블에 초기 데이터 저장 (status: processing)
|
||||
3. Creatomate API 호출 (orientation에 따른 템플릿 자동 선택)
|
||||
4. creatomate_render_id 업데이트 후 응답 반환
|
||||
|
||||
Note: 이 함수는 Depends(get_session)을 사용하지 않고 명시적으로 세션을 관리합니다.
|
||||
외부 API 호출 중 DB 커넥션이 유지되지 않도록 하여 커넥션 타임아웃 문제를 방지합니다.
|
||||
DB 쿼리는 asyncio.gather()를 사용하여 병렬로 실행됩니다.
|
||||
"""
|
||||
import asyncio
|
||||
|
||||
from app.database.session import AsyncSessionLocal
|
||||
|
||||
print(f"[generate_video] START - task_id: {task_id}, orientation: {orientation}")
|
||||
|
||||
# ==========================================================================
|
||||
# 1단계: DB 조회 및 초기 데이터 저장 (세션을 명시적으로 열고 닫음)
|
||||
# ==========================================================================
|
||||
# 외부 API 호출 전에 필요한 데이터를 저장할 변수들
|
||||
project_id: int | None = None
|
||||
lyric_id: int | None = None
|
||||
song_id: int | None = None
|
||||
video_id: int | None = None
|
||||
music_url: str | None = None
|
||||
song_duration: float | None = None
|
||||
lyrics: str | None = None
|
||||
image_urls: list[str] = []
|
||||
|
||||
try:
|
||||
# 1. task_id로 Project 조회 (중복 시 최신 것 선택)
|
||||
project_result = await session.execute(
|
||||
select(Project)
|
||||
.where(Project.task_id == task_id)
|
||||
.order_by(Project.created_at.desc())
|
||||
.limit(1)
|
||||
)
|
||||
project = project_result.scalar_one_or_none()
|
||||
# 세션을 명시적으로 열고 DB 작업 후 바로 닫음
|
||||
async with AsyncSessionLocal() as session:
|
||||
# ===== 병렬 쿼리 실행: Project, Lyric, Song, Image 동시 조회 =====
|
||||
project_query = select(Project).where(
|
||||
Project.task_id == task_id
|
||||
).order_by(Project.created_at.desc()).limit(1)
|
||||
|
||||
if not project:
|
||||
print(f"[generate_video] Project NOT FOUND - task_id: {task_id}")
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"task_id '{task_id}'에 해당하는 Project를 찾을 수 없습니다.",
|
||||
lyric_query = select(Lyric).where(
|
||||
Lyric.task_id == task_id
|
||||
).order_by(Lyric.created_at.desc()).limit(1)
|
||||
|
||||
song_query = select(Song).where(
|
||||
Song.task_id == task_id
|
||||
).order_by(Song.created_at.desc()).limit(1)
|
||||
|
||||
image_query = select(Image).where(
|
||||
Image.task_id == task_id
|
||||
).order_by(Image.img_order.asc())
|
||||
|
||||
# 4개 쿼리를 병렬로 실행
|
||||
project_result, lyric_result, song_result, image_result = (
|
||||
await asyncio.gather(
|
||||
session.execute(project_query),
|
||||
session.execute(lyric_query),
|
||||
session.execute(song_query),
|
||||
session.execute(image_query),
|
||||
)
|
||||
)
|
||||
print(f"[generate_video] Project found - project_id: {project.id}, task_id: {task_id}")
|
||||
print(f"[generate_video] Parallel queries completed - task_id: {task_id}")
|
||||
|
||||
# 2. task_id로 Lyric 조회 (중복 시 최신 것 선택)
|
||||
lyric_result = await session.execute(
|
||||
select(Lyric)
|
||||
.where(Lyric.task_id == task_id)
|
||||
.order_by(Lyric.created_at.desc())
|
||||
.limit(1)
|
||||
)
|
||||
lyric = lyric_result.scalar_one_or_none()
|
||||
# ===== 결과 처리: Project =====
|
||||
project = project_result.scalar_one_or_none()
|
||||
if not project:
|
||||
print(f"[generate_video] Project NOT FOUND - task_id: {task_id}")
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"task_id '{task_id}'에 해당하는 Project를 찾을 수 없습니다.",
|
||||
)
|
||||
project_id = project.id
|
||||
|
||||
if not lyric:
|
||||
print(f"[generate_video] Lyric NOT FOUND - task_id: {task_id}")
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"task_id '{task_id}'에 해당하는 Lyric을 찾을 수 없습니다.",
|
||||
)
|
||||
print(f"[generate_video] Lyric found - lyric_id: {lyric.id}, task_id: {task_id}")
|
||||
# ===== 결과 처리: Lyric =====
|
||||
lyric = lyric_result.scalar_one_or_none()
|
||||
if not lyric:
|
||||
print(f"[generate_video] Lyric NOT FOUND - task_id: {task_id}")
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"task_id '{task_id}'에 해당하는 Lyric을 찾을 수 없습니다.",
|
||||
)
|
||||
lyric_id = lyric.id
|
||||
|
||||
# 3. task_id로 Song 조회 (가장 최근 것)
|
||||
song_result = await session.execute(
|
||||
select(Song)
|
||||
.where(Song.task_id == task_id)
|
||||
.order_by(Song.created_at.desc())
|
||||
.limit(1)
|
||||
)
|
||||
song = song_result.scalar_one_or_none()
|
||||
# ===== 결과 처리: Song =====
|
||||
song = song_result.scalar_one_or_none()
|
||||
if not song:
|
||||
print(f"[generate_video] Song NOT FOUND - task_id: {task_id}")
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"task_id '{task_id}'에 해당하는 Song을 찾을 수 없습니다.",
|
||||
)
|
||||
|
||||
if not song:
|
||||
print(f"[generate_video] Song NOT FOUND - task_id: {task_id}")
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"task_id '{task_id}'에 해당하는 Song을 찾을 수 없습니다.",
|
||||
song_id = song.id
|
||||
music_url = song.song_result_url
|
||||
song_duration = song.duration
|
||||
lyrics = song.song_prompt
|
||||
|
||||
if not music_url:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Song(id={song_id})의 음악 URL이 없습니다.",
|
||||
)
|
||||
|
||||
if not lyrics:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Song(id={song_id})의 가사(song_prompt)가 없습니다.",
|
||||
)
|
||||
|
||||
# ===== 결과 처리: Image =====
|
||||
images = image_result.scalars().all()
|
||||
if not images:
|
||||
print(f"[generate_video] Image NOT FOUND - task_id: {task_id}")
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"task_id '{task_id}'에 해당하는 이미지를 찾을 수 없습니다.",
|
||||
)
|
||||
image_urls = [img.img_url for img in images]
|
||||
|
||||
print(
|
||||
f"[generate_video] Data loaded - task_id: {task_id}, "
|
||||
f"project_id: {project_id}, lyric_id: {lyric_id}, "
|
||||
f"song_id: {song_id}, images: {len(image_urls)}"
|
||||
)
|
||||
|
||||
# Song에서 music_url과 duration 가져오기
|
||||
music_url = song.song_result_url
|
||||
if not music_url:
|
||||
print(f"[generate_video] Song has no result URL - task_id: {task_id}, song_id: {song.id}")
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Song(id={song.id})의 음악 URL이 없습니다. 노래 생성이 완료되었는지 확인하세요.",
|
||||
# ===== Video 테이블에 초기 데이터 저장 및 커밋 =====
|
||||
video = Video(
|
||||
project_id=project_id,
|
||||
lyric_id=lyric_id,
|
||||
song_id=song_id,
|
||||
task_id=task_id,
|
||||
creatomate_render_id=None,
|
||||
status="processing",
|
||||
)
|
||||
session.add(video)
|
||||
await session.commit()
|
||||
video_id = video.id
|
||||
print(f"[generate_video] Video saved - task_id: {task_id}, id: {video_id}")
|
||||
# 세션이 여기서 자동으로 닫힘 (async with 블록 종료)
|
||||
|
||||
# Song에서 가사(song_prompt) 가져오기
|
||||
lyrics = song.song_prompt
|
||||
if not lyrics:
|
||||
print(f"[generate_video] Song has no lyrics (song_prompt) - task_id: {task_id}, song_id: {song.id}")
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Song(id={song.id})의 가사(song_prompt)가 없습니다.",
|
||||
)
|
||||
|
||||
print(f"[generate_video] Song found - song_id: {song.id}, task_id: {task_id}, duration: {song.duration}")
|
||||
print(f"[generate_video] Music URL (from DB): {music_url}, Song duration: {song.duration}, Lyrics length: {len(lyrics)}")
|
||||
|
||||
# 4. task_id로 Image 조회 (img_order 순서로 정렬)
|
||||
image_result = await session.execute(
|
||||
select(Image)
|
||||
.where(Image.task_id == task_id)
|
||||
.order_by(Image.img_order.asc())
|
||||
)
|
||||
images = image_result.scalars().all()
|
||||
|
||||
if not images:
|
||||
print(f"[generate_video] Image NOT FOUND - task_id: {task_id}")
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"task_id '{task_id}'에 해당하는 이미지를 찾을 수 없습니다.",
|
||||
)
|
||||
|
||||
image_urls = [img.img_url for img in images]
|
||||
print(f"[generate_video] Images found - task_id: {task_id}, count: {len(image_urls)}")
|
||||
|
||||
# 5. Video 테이블에 초기 데이터 저장
|
||||
video = Video(
|
||||
project_id=project.id,
|
||||
lyric_id=lyric.id,
|
||||
song_id=song.id,
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
print(f"[generate_video] DB EXCEPTION - task_id: {task_id}, error: {e}")
|
||||
return GenerateVideoResponse(
|
||||
success=False,
|
||||
task_id=task_id,
|
||||
creatomate_render_id=None,
|
||||
status="processing",
|
||||
message="영상 생성 요청에 실패했습니다.",
|
||||
error_message=str(e),
|
||||
)
|
||||
session.add(video)
|
||||
await session.flush() # ID 생성을 위해 flush
|
||||
print(f"[generate_video] Video saved (processing) - task_id: {task_id}")
|
||||
|
||||
# 6. Creatomate API 호출 (POC 패턴 적용)
|
||||
# ==========================================================================
|
||||
# 2단계: 외부 API 호출 (세션 사용 안함 - 커넥션 풀 점유 없음)
|
||||
# ==========================================================================
|
||||
try:
|
||||
print(f"[generate_video] Creatomate API generation started - task_id: {task_id}")
|
||||
# orientation에 따른 템플릿 선택, duration은 Song에서 가져옴 (없으면 config 기본값 사용)
|
||||
creatomate_service = CreatomateService(
|
||||
orientation=orientation,
|
||||
target_duration=song.duration, # Song의 duration 사용 (None이면 config 기본값)
|
||||
target_duration=song_duration,
|
||||
)
|
||||
print(f"[generate_video] Using template_id: {creatomate_service.template_id}, duration: {creatomate_service.target_duration} (song duration: {song.duration})")
|
||||
print(f"[generate_video] Using template_id: {creatomate_service.template_id}, duration: {creatomate_service.target_duration} (song duration: {song_duration})")
|
||||
|
||||
# 6-1. 템플릿 조회 (비동기, CreatomateService에서 orientation에 맞는 template_id 사용)
|
||||
# 6-1. 템플릿 조회 (비동기)
|
||||
template = await creatomate_service.get_one_template_data_async(creatomate_service.template_id)
|
||||
print(f"[generate_video] Template fetched - task_id: {task_id}")
|
||||
|
||||
# 6-2. elements에서 리소스 매핑 생성 (music_url, lyrics는 DB에서 조회한 값 사용)
|
||||
# 6-2. elements에서 리소스 매핑 생성
|
||||
modifications = creatomate_service.elements_connect_resource_blackbox(
|
||||
elements=template["source"]["elements"],
|
||||
image_url_list=image_urls,
|
||||
@@ -239,7 +279,7 @@ async def generate_video(
|
||||
template["source"]["elements"] = new_elements
|
||||
print(f"[generate_video] Elements modified - task_id: {task_id}")
|
||||
|
||||
# 6-4. duration 확장 (target_duration: 영상 길이)
|
||||
# 6-4. duration 확장
|
||||
final_template = creatomate_service.extend_template_duration(
|
||||
template,
|
||||
creatomate_service.target_duration,
|
||||
@@ -252,7 +292,7 @@ async def generate_video(
|
||||
)
|
||||
print(f"[generate_video] Creatomate API response - task_id: {task_id}, response: {render_response}")
|
||||
|
||||
# 렌더 ID 추출 (응답이 리스트인 경우 첫 번째 항목 사용)
|
||||
# 렌더 ID 추출
|
||||
if isinstance(render_response, list) and len(render_response) > 0:
|
||||
creatomate_render_id = render_response[0].get("id")
|
||||
elif isinstance(render_response, dict):
|
||||
@@ -260,9 +300,39 @@ async def generate_video(
|
||||
else:
|
||||
creatomate_render_id = None
|
||||
|
||||
# 7. creatomate_render_id 업데이트
|
||||
video.creatomate_render_id = creatomate_render_id
|
||||
await session.commit()
|
||||
except Exception as e:
|
||||
print(f"[generate_video] Creatomate API EXCEPTION - task_id: {task_id}, error: {e}")
|
||||
# 외부 API 실패 시 Video 상태를 failed로 업데이트
|
||||
from app.database.session import AsyncSessionLocal
|
||||
async with AsyncSessionLocal() as update_session:
|
||||
video_result = await update_session.execute(
|
||||
select(Video).where(Video.id == video_id)
|
||||
)
|
||||
video_to_update = video_result.scalar_one_or_none()
|
||||
if video_to_update:
|
||||
video_to_update.status = "failed"
|
||||
await update_session.commit()
|
||||
return GenerateVideoResponse(
|
||||
success=False,
|
||||
task_id=task_id,
|
||||
creatomate_render_id=None,
|
||||
message="영상 생성 요청에 실패했습니다.",
|
||||
error_message=str(e),
|
||||
)
|
||||
|
||||
# ==========================================================================
|
||||
# 3단계: creatomate_render_id 업데이트 (새 세션으로 빠르게 처리)
|
||||
# ==========================================================================
|
||||
try:
|
||||
from app.database.session import AsyncSessionLocal
|
||||
async with AsyncSessionLocal() as update_session:
|
||||
video_result = await update_session.execute(
|
||||
select(Video).where(Video.id == video_id)
|
||||
)
|
||||
video_to_update = video_result.scalar_one_or_none()
|
||||
if video_to_update:
|
||||
video_to_update.creatomate_render_id = creatomate_render_id
|
||||
await update_session.commit()
|
||||
print(f"[generate_video] SUCCESS - task_id: {task_id}, creatomate_render_id: {creatomate_render_id}")
|
||||
|
||||
return GenerateVideoResponse(
|
||||
@@ -273,16 +343,13 @@ async def generate_video(
|
||||
error_message=None,
|
||||
)
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
print(f"[generate_video] EXCEPTION - task_id: {task_id}, error: {e}")
|
||||
await session.rollback()
|
||||
print(f"[generate_video] Update EXCEPTION - task_id: {task_id}, error: {e}")
|
||||
return GenerateVideoResponse(
|
||||
success=False,
|
||||
task_id=task_id,
|
||||
creatomate_render_id=None,
|
||||
message="영상 생성 요청에 실패했습니다.",
|
||||
creatomate_render_id=creatomate_render_id,
|
||||
message="영상 생성은 요청되었으나 DB 업데이트에 실패했습니다.",
|
||||
error_message=str(e),
|
||||
)
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ import aiofiles
|
||||
import httpx
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.database.session import AsyncSessionLocal
|
||||
from app.database.session import BackgroundSessionLocal
|
||||
from app.video.models import Video
|
||||
from app.utils.upload_blob_as_request import AzureBlobUploader
|
||||
|
||||
@@ -66,7 +66,7 @@ async def download_and_upload_video_to_blob(
|
||||
print(f"[download_and_upload_video_to_blob] Uploaded to Blob - task_id: {task_id}, url: {blob_url}")
|
||||
|
||||
# Video 테이블 업데이트 (새 세션 사용)
|
||||
async with AsyncSessionLocal() as session:
|
||||
async with BackgroundSessionLocal() as session:
|
||||
# 여러 개 있을 경우 가장 최근 것 선택
|
||||
result = await session.execute(
|
||||
select(Video)
|
||||
@@ -87,7 +87,7 @@ async def download_and_upload_video_to_blob(
|
||||
except Exception as e:
|
||||
print(f"[download_and_upload_video_to_blob] EXCEPTION - task_id: {task_id}, error: {e}")
|
||||
# 실패 시 Video 테이블 업데이트
|
||||
async with AsyncSessionLocal() as session:
|
||||
async with BackgroundSessionLocal() as session:
|
||||
result = await session.execute(
|
||||
select(Video)
|
||||
.where(Video.task_id == task_id)
|
||||
@@ -137,7 +137,7 @@ async def download_and_upload_video_by_creatomate_render_id(
|
||||
|
||||
try:
|
||||
# creatomate_render_id로 Video 조회하여 task_id 가져오기
|
||||
async with AsyncSessionLocal() as session:
|
||||
async with BackgroundSessionLocal() as session:
|
||||
result = await session.execute(
|
||||
select(Video)
|
||||
.where(Video.creatomate_render_id == creatomate_render_id)
|
||||
@@ -188,7 +188,7 @@ async def download_and_upload_video_by_creatomate_render_id(
|
||||
print(f"[download_and_upload_video_by_creatomate_render_id] Uploaded to Blob - creatomate_render_id: {creatomate_render_id}, url: {blob_url}")
|
||||
|
||||
# Video 테이블 업데이트 (새 세션 사용)
|
||||
async with AsyncSessionLocal() as session:
|
||||
async with BackgroundSessionLocal() as session:
|
||||
result = await session.execute(
|
||||
select(Video)
|
||||
.where(Video.creatomate_render_id == creatomate_render_id)
|
||||
@@ -209,7 +209,7 @@ async def download_and_upload_video_by_creatomate_render_id(
|
||||
print(f"[download_and_upload_video_by_creatomate_render_id] EXCEPTION - creatomate_render_id: {creatomate_render_id}, error: {e}")
|
||||
# 실패 시 Video 테이블 업데이트
|
||||
if task_id:
|
||||
async with AsyncSessionLocal() as session:
|
||||
async with BackgroundSessionLocal() as session:
|
||||
result = await session.execute(
|
||||
select(Video)
|
||||
.where(Video.creatomate_render_id == creatomate_render_id)
|
||||
|
||||
Reference in new issue
Block a user