chwellofficial/nt360Slides
0
1from pathlib import Path2from typing import List3from fastapi import HTTPException4 5from fastapi import UploadFile6 7 8def _is_accepted_file_type(file: UploadFile, accepted_types: List[str]) -> bool:9 accepted_mime_types = {t.lower() for t in accepted_types if not t.startswith(".")}10 accepted_extensions = {t.lower() for t in accepted_types if t.startswith(".")}11 12 content_type = (file.content_type or "").strip().lower()13 if content_type in accepted_mime_types:14 return True15 16 extension = Path(file.filename or "").suffix.lower()17 if extension in accepted_extensions:18 return True19 20 return False21 22 23def validate_files(24 field,25 nullable: bool,26 multiple: bool,27 max_size: int,28 accepted_types: List[str],29):30 31 if field:32 files: List[UploadFile] = field if multiple else [field]33 for each_file in files:34 file_size = each_file.size or 035 36 if (max_size * 1024 * 1024) < file_size:37 raise HTTPException(38 400,39 detail=f"File '{each_file.filename}' exceeded max upload size of {max_size} MB",40 )41 elif not _is_accepted_file_type(each_file, accepted_types):42 raise HTTPException(43 400,44 detail=f"File '{each_file.filename}' not accepted. Accepted types: {accepted_types}",45 )46 47 elif not (field or nullable):48 raise HTTPException(400, detail="File must be provided.")49 