59 lines
1.9 KiB
Python
59 lines
1.9 KiB
Python
# utils/file_utils.py
|
|
|
|
from pathlib import Path
|
|
|
|
from fastapi import HTTPException, UploadFile
|
|
from snowflake import SnowflakeGenerator
|
|
from utils.config import ALLOWED_EXTENSIONS, RESULT_DIR, UPLOAD_DOCS_DIR
|
|
|
|
|
|
def create_essential_directories():
|
|
"""애플리케이션 시작 시 필요한 디렉토리를 생성합니다."""
|
|
UPLOAD_DOCS_DIR.mkdir(exist_ok=True)
|
|
RESULT_DIR.mkdir(exist_ok=True)
|
|
|
|
|
|
def create_key(node=1):
|
|
generator = SnowflakeGenerator(node)
|
|
key_value = next(generator)
|
|
return str(key_value)
|
|
|
|
|
|
def save_uploaded_file(
|
|
upload_file: UploadFile, save_dir: Path, file_prefix: str
|
|
) -> tuple[str, bytes]:
|
|
"""
|
|
업로드된 파일을 지정된 디렉토리에 저장하고, 파일 내용을 바이트로 반환합니다.
|
|
|
|
Returns:
|
|
저장된 파일 경로 (str), 파일 내용 (bytes)
|
|
"""
|
|
file_extension = Path(upload_file.filename).suffix.lower()
|
|
if file_extension not in ALLOWED_EXTENSIONS:
|
|
raise HTTPException(
|
|
status_code=400,
|
|
detail=f"지원하지 않는 파일 형식이에요. 지원 형식: {', '.join(ALLOWED_EXTENSIONS)} 😢",
|
|
)
|
|
|
|
new_filename = f"{file_prefix}{file_extension}"
|
|
file_path = save_dir / new_filename
|
|
|
|
try:
|
|
upload_file.file.seek(0)
|
|
file_content = upload_file.file.read() # 내용을 읽음
|
|
|
|
with open(file_path, "wb") as buffer:
|
|
buffer.write(file_content) # 내용을 저장
|
|
|
|
print(f"File saved: {file_path}")
|
|
return str(file_path), file_content
|
|
|
|
except IOError as e:
|
|
print(f"File saving error for {file_prefix}: {e}", exc_info=True)
|
|
raise HTTPException(status_code=500, detail=f"파일 저장 중 오류 발생: {str(e)}")
|
|
except Exception as e:
|
|
print(f"Unexpected file saving error for {file_prefix}: {e}", exc_info=True)
|
|
raise HTTPException(
|
|
status_code=500, detail=f"파일 처리 중 예상치 못한 오류 발생: {str(e)}"
|
|
)
|