Refactor file relocation logic for theme-specific files.
All checks were successful
Build and Push Docker Images / changes (push) Successful in 4s
Build and Push Docker Images / build-backend (push) Successful in 49s
Build and Push Docker Images / build-frontend (push) Has been skipped

Updated the file relocation function to use `settings.DATA_FILES_DIR` for theme folders and improved filename handling by prefixing with the file type. Adjusted logic to handle URLs consistently and ensure paths are properly resolved. This enhances maintainability and organizes theme files more effectively.
This commit is contained in:
2025-03-14 02:22:21 +01:00
parent 3244fd8beb
commit d2e71feb69

View File

@@ -29,6 +29,7 @@ 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
def _relocate_theme_file(theme_id: uuid.UUID, current_url: str, file_type: str, storage: StorageProvider) -> str:
"""
Move an uploaded file to a theme-specific folder.
@@ -44,26 +45,34 @@ def _relocate_theme_file(theme_id: uuid.UUID, current_url: str, file_type: str,
"""
try:
# Extract the filename from the URL
current_file = current_url.split('/files/')[1] if '/files/' in current_url else current_url
if 'uploads/' in current_url:
# Extract the part after 'uploads/'
current_file = current_url.split('uploads/')[1]
else:
current_file = current_url
filename = os.path.basename(current_file)
# Define source and destination paths
source_path = os.path.join(storage.upload_folder, current_file)
theme_folder = os.path.join(storage.upload_folder, f'event-themes/{theme_id}/{file_type}')
# Use settings.DATA_FILES_DIR for theme files
theme_folder = os.path.join(settings.DATA_FILES_DIR, f'event-themes/{theme_id}')
# Create the destination folder if it doesn't exist
os.makedirs(theme_folder, exist_ok=True)
# Define destination path
dest_path = os.path.join(theme_folder, filename)
prefixed_filename = f"{file_type}_{filename}"
dest_path = os.path.join(theme_folder, prefixed_filename)
# Move the file
if os.path.exists(source_path):
shutil.move(source_path, dest_path)
# Return the new URL
relative_path = os.path.relpath(dest_path, storage.upload_folder)
return f"/files/{relative_path}"
# Return the new URL - relative to the upload folder
relative_path = os.path.relpath(dest_path, settings.DATA_FILES_DIR)
return relative_path
return None
except Exception as e: