54 lines
1.4 KiB
Python
54 lines
1.4 KiB
Python
"""
|
|
File validation utilities
|
|
"""
|
|
from werkzeug.utils import secure_filename
|
|
from pathlib import Path
|
|
from typing import Optional, List, Tuple
|
|
|
|
def is_allowed_file(filename: str, allowed_extensions: List[str]) -> bool:
|
|
"""
|
|
Check if file extension is allowed
|
|
|
|
Args:
|
|
filename: File name
|
|
allowed_extensions: List of allowed extensions
|
|
|
|
Returns:
|
|
True if extension is allowed, False otherwise
|
|
"""
|
|
if '.' not in filename:
|
|
return False
|
|
ext = filename.rsplit('.', 1)[1].lower()
|
|
return ext in allowed_extensions
|
|
|
|
def validate_file_size(file_size: int, max_size: int) -> Tuple[bool, Optional[str]]:
|
|
"""
|
|
Validate file size
|
|
|
|
Args:
|
|
file_size: File size in bytes
|
|
max_size: Maximum allowed size in bytes
|
|
|
|
Returns:
|
|
Tuple of (is_valid, error_message)
|
|
"""
|
|
if file_size > max_size:
|
|
max_size_mb = max_size / (1024 * 1024)
|
|
return False, f"File size exceeds maximum allowed size of {max_size_mb:.1f}MB"
|
|
return True, None
|
|
|
|
def secure_file_path(filename: str, upload_folder: Path) -> Path:
|
|
"""
|
|
Generate secure file path
|
|
|
|
Args:
|
|
filename: Original filename
|
|
upload_folder: Upload folder path
|
|
|
|
Returns:
|
|
Secure file path
|
|
"""
|
|
secure_name = secure_filename(filename)
|
|
return upload_folder / secure_name
|
|
|