Add file utility functions for filename and path handling
Introduce helper functions to generate unique filenames, create date-based storage paths, and validate image content types. These utilities centralize and streamline file-related operations for consistency and reusability.
This commit is contained in:
28
backend/app/utils/files.py
Normal file
28
backend/app/utils/files.py
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import os
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from app.core.config import settings
|
||||||
|
|
||||||
|
|
||||||
|
def generate_unique_filename(original_filename: str) -> str:
|
||||||
|
"""Generate a unique filename preserving the original extension."""
|
||||||
|
name, ext = os.path.splitext(original_filename)
|
||||||
|
unique_id = uuid.uuid4().hex
|
||||||
|
return f"{unique_id}{ext}"
|
||||||
|
|
||||||
|
|
||||||
|
def get_relative_storage_path(folder: str, filename: str) -> str:
|
||||||
|
"""
|
||||||
|
Generate a relative storage path using date-based organization.
|
||||||
|
|
||||||
|
Example: "event-themes/2023/03/filename.jpg"
|
||||||
|
"""
|
||||||
|
today = datetime.now()
|
||||||
|
year_month = today.strftime("%Y/%m")
|
||||||
|
return os.path.join(folder, year_month, filename)
|
||||||
|
|
||||||
|
|
||||||
|
def validate_image_content_type(content_type: str) -> bool:
|
||||||
|
"""Check if the content type is an allowed image type."""
|
||||||
|
return content_type in settings.ALLOWED_IMAGE_TYPES
|
||||||
Reference in New Issue
Block a user