o2o-castad-backend/app/home/worker/home_task.py

59 lines
1.6 KiB
Python

"""
Home Worker 모듈
이미지 업로드 관련 백그라운드 작업을 처리합니다.
"""
from pathlib import Path
import aiofiles
from fastapi import UploadFile
from app.utils.upload_blob_as_request import AzureBlobUploader
async def save_upload_file(file: UploadFile, save_path: Path) -> None:
"""업로드 파일을 지정된 경로에 저장"""
save_path.parent.mkdir(parents=True, exist_ok=True)
async with aiofiles.open(save_path, "wb") as f:
content = await file.read()
await f.write(content)
async def upload_image_to_blob(
task_id: str,
file: UploadFile,
filename: str,
save_dir: Path,
) -> tuple[bool, str, str]:
"""
이미지 파일을 media에 저장하고 Azure Blob Storage에 업로드합니다.
Args:
task_id: 작업 고유 식별자
file: 업로드할 파일 객체
filename: 저장될 파일명
save_dir: media 저장 디렉토리 경로
Returns:
tuple[bool, str, str]: (업로드 성공 여부, blob_url 또는 에러 메시지, media_path)
"""
save_path = save_dir / filename
media_path = str(save_path)
try:
# 1. media에 파일 저장
await save_upload_file(file, save_path)
# 2. Azure Blob Storage에 업로드
uploader = AzureBlobUploader(task_id=task_id)
upload_success = await uploader.upload_image(file_path=str(save_path))
if upload_success:
return True, uploader.public_url, media_path
else:
return False, f"Failed to upload {filename} to Blob", media_path
except Exception as e:
return False, str(e), media_path