Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /nijaru_zenith /docs /examples /06-file-upload.py
| """ | |
| Enhanced file upload example for Zenith. | |
| Demonstrates modern file upload handling with improved UX, | |
| showing both the enhanced UploadedFile API and traditional patterns. | |
| This addresses common pain points found in production applications. | |
| """ | |
| import uuid | |
| from pathlib import Path | |
| from pydantic import BaseModel | |
| from starlette.datastructures import UploadFile | |
| from zenith import File, Zenith | |
| from zenith.exceptions import HTTPException | |
| from zenith.web.files import UploadedFile | |
| # Create app | |
| app = Zenith() | |
| # Upload directory | |
| UPLOAD_DIR = Path("uploads") | |
| UPLOAD_DIR.mkdir(exist_ok=True) | |
| # Allowed file types | |
| ALLOWED_IMAGES = {".jpg", ".jpeg", ".png", ".gif", ".webp"} | |
| ALLOWED_DOCUMENTS = {".pdf", ".doc", ".docx", ".txt", ".md"} | |
| class FileInfo(BaseModel): | |
| """Enhanced file upload response.""" | |
| filename: str | |
| original_filename: str | |
| size_bytes: int | |
| content_type: str | |
| saved_path: str | |
| file_type: str # image, audio, video, document, other | |
| url: str | None = None | |
| def get_file_type(file: UploadedFile | UploadFile) -> str: | |
| """Determine the general file type from content type or extension.""" | |
| if hasattr(file, "is_image") and file.is_image(): | |
| return "image" | |
| elif hasattr(file, "is_audio") and file.is_audio(): | |
| return "audio" | |
| elif hasattr(file, "is_video") and file.is_video(): | |
| return "video" | |
| elif hasattr(file, "is_pdf") and file.is_pdf(): | |
| return "document" | |
| elif hasattr(file, "content_type") and file.content_type: | |
| if file.content_type.startswith("image/"): | |
| return "image" | |
| elif file.content_type.startswith("audio/"): | |
| return "audio" | |
| elif file.content_type.startswith("video/"): | |
| return "video" | |
| elif "pdf" in file.content_type: | |
| return "document" | |
| return "other" | |
| async def upload_modern( | |
| file: UploadedFile = File( | |
| max_size=10 * 1024 * 1024, # 10MB | |
| allowed_types=[ | |
| "image/jpeg", | |
| "image/png", | |
| "audio/mpeg", | |
| "audio/wav", | |
| "application/pdf", | |
| ], | |
| ), | |
| ) -> FileInfo: | |
| """ | |
| Modern file upload using enhanced UploadedFile API. | |
| This demonstrates the improved UX with automatic validation | |
| and convenient file handling methods. | |
| """ | |
| # Generate UUID-based filename to avoid conflicts | |
| file_id = str(uuid.uuid4()) | |
| extension = file.get_extension() | |
| safe_filename = f"{file_id}{extension}" | |
| # Use convenient move_to method (much cleaner than manual file handling) | |
| final_path = await file.move_to(UPLOAD_DIR / safe_filename) | |
| return FileInfo( | |
| filename=safe_filename, | |
| original_filename=file.original_filename, | |
| size_bytes=file.size_bytes, | |
| content_type=file.content_type, | |
| saved_path=str(final_path), | |
| file_type=get_file_type(file), | |
| url=f"/files/{safe_filename}", | |
| ) | |
| async def upload_image(file: UploadFile = File()) -> FileInfo: | |
| """Upload a single image file (traditional approach for comparison).""" | |
| # Validate file type | |
| ext = Path(file.filename).suffix.lower() | |
| if ext not in ALLOWED_IMAGES: | |
| raise HTTPException( | |
| 400, f"Invalid image type. Allowed: {', '.join(ALLOWED_IMAGES)}" | |
| ) | |
| # Validate file size (5MB max) | |
| contents = await file.read() | |
| if len(contents) > 5 * 1024 * 1024: | |
| raise HTTPException(413, "File too large. Maximum size: 5MB") | |
| # Save file | |
| save_path = UPLOAD_DIR / f"image_{file.filename}" | |
| with Path(save_path).open("wb") as f: | |
| f.write(contents) | |
| return FileInfo( | |
| filename=file.filename, | |
| original_filename=file.filename, | |
| size_bytes=len(contents), | |
| content_type=file.content_type, | |
| saved_path=str(save_path), | |
| file_type=get_file_type(file), | |
| ) | |
| async def upload_document(file: UploadFile = File()) -> FileInfo: | |
| """Upload a document file.""" | |
| # Validate file type | |
| ext = Path(file.filename).suffix.lower() | |
| if ext not in ALLOWED_DOCUMENTS: | |
| raise ValueError( | |
| f"Invalid document type. Allowed: {', '.join(ALLOWED_DOCUMENTS)}" | |
| ) | |
| # Read and save | |
| contents = await file.read() | |
| save_path = UPLOAD_DIR / f"doc_{file.filename}" | |
| with Path(save_path).open("wb") as f: | |
| f.write(contents) | |
| return FileInfo( | |
| filename=file.filename, | |
| size_bytes=len(contents), | |
| content_type=file.content_type, | |
| saved_path=str(save_path), | |
| ) | |
| async def upload_multiple(files: list[UploadFile] = File()) -> list[FileInfo]: | |
| """Upload multiple files at once.""" | |
| results = [] | |
| for file in files: | |
| # Save each file | |
| contents = await file.read() | |
| save_path = UPLOAD_DIR / f"multi_{file.filename}" | |
| with Path(save_path).open("wb") as f: | |
| f.write(contents) | |
| results.append( | |
| FileInfo( | |
| filename=file.filename, | |
| size_bytes=len(contents), | |
| content_type=file.content_type, | |
| saved_path=str(save_path), | |
| ) | |
| ) | |
| return results | |
| async def upload_profile( | |
| username: str, bio: str | None = None, avatar: UploadFile = File() | |
| ) -> dict: | |
| """Upload profile with avatar image (mixed form data).""" | |
| # Validate avatar | |
| ext = Path(avatar.filename).suffix.lower() | |
| if ext not in ALLOWED_IMAGES: | |
| raise ValueError("Avatar must be an image file") | |
| # Save avatar | |
| contents = await avatar.read() | |
| avatar_path = UPLOAD_DIR / f"avatar_{username}{ext}" | |
| with Path(avatar_path).open("wb") as f: | |
| f.write(contents) | |
| return { | |
| "username": username, | |
| "bio": bio or "No bio provided", | |
| "avatar": str(avatar_path), | |
| "avatar_size_bytes": len(contents), | |
| } | |
| async def list_files() -> list[dict]: | |
| """List all uploaded files.""" | |
| files = [] | |
| for filepath in UPLOAD_DIR.iterdir(): | |
| if filepath.is_file(): | |
| stat = filepath.stat() | |
| files.append( | |
| { | |
| "name": filepath.name, | |
| "size_bytes": stat.st_size, | |
| "modified": stat.st_mtime, | |
| } | |
| ) | |
| return files | |
| async def delete_file(filename: str) -> dict: | |
| """Delete an uploaded file.""" | |
| filepath = UPLOAD_DIR / filename | |
| if not filepath.exists(): | |
| raise ValueError(f"File {filename} not found") | |
| Path(filepath).unlink() | |
| return {"message": f"File {filename} deleted"} | |
| async def health() -> dict: | |
| return {"status": "healthy", "upload_dir": str(UPLOAD_DIR)} | |
| if __name__ == "__main__": | |
| import uvicorn | |
| print("📁 Enhanced File Upload Example") | |
| print("Upload directory:", UPLOAD_DIR.absolute()) | |
| print("\nEndpoints:") | |
| print(" POST /upload/modern - Modern enhanced upload (recommended)") | |
| print(" POST /upload/image - Upload single image (traditional)") | |
| print(" POST /upload/document - Upload document") | |
| print(" POST /upload/multiple - Upload multiple files") | |
| print(" POST /upload/profile - Mixed form with file") | |
| print(" GET /files - List uploaded files") | |
| print(" DELETE /files/{filename} - Delete file") | |
| print("\nTest with curl:") | |
| print(" # Modern enhanced API:") | |
| print(' curl -X POST -F "file=@song.mp3" http://localhost:8006/upload/modern') | |
| print(' curl -X POST -F "file=@document.pdf" http://localhost:8006/upload/modern') | |
| print() | |
| print(" # Traditional API:") | |
| print(' curl -X POST -F "file=@image.jpg" http://localhost:8006/upload/image') | |
| uvicorn.run("file_upload_example:app", host="127.0.0.1", port=8006, reload=True) | |
Xet Storage Details
- Size:
- 7.92 kB
- Xet hash:
- 6a7d18d055e479fe81a845fc229645532f296c4150db8db5c3c7d6261daa6cf2
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.