33 lines
1.0 KiB
Python
33 lines
1.0 KiB
Python
import re
|
|
import os
|
|
import uuid
|
|
from pathlib import Path
|
|
|
|
def generate_slug(text: str) -> str:
|
|
"""Generate a URL-friendly slug from text"""
|
|
# Convert to lowercase
|
|
slug = text.lower()
|
|
# Replace spaces and special characters with hyphens
|
|
slug = re.sub(r'[^\w\s-]', '', slug)
|
|
slug = re.sub(r'[\s_-]+', '-', slug)
|
|
slug = re.sub(r'^-+|-+$', '', slug)
|
|
return slug
|
|
|
|
def save_upload_file(upload_file, folder: str = "products") -> str:
|
|
"""Save uploaded file and return the file path"""
|
|
# Create uploads directory if it doesn't exist
|
|
upload_dir = Path("uploads") / folder
|
|
upload_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
# Generate unique filename
|
|
file_extension = os.path.splitext(upload_file.filename)[1]
|
|
unique_filename = f"{uuid.uuid4()}{file_extension}"
|
|
file_path = upload_dir / unique_filename
|
|
|
|
# Save file
|
|
with open(file_path, "wb") as buffer:
|
|
buffer.write(upload_file.file.read())
|
|
|
|
# Return relative path for URL
|
|
return f"/uploads/{folder}/{unique_filename}"
|