Performance: File validation (size, type)
MEDIUM IMPACT
This affects page load speed and interaction responsiveness by preventing large or invalid files from being processed or uploaded.
from fastapi import FastAPI, File, UploadFile, HTTPException app = FastAPI() MAX_SIZE = 5_000_000 @app.post('/upload') async def upload_file(file: UploadFile = File(...)): if not file.content_type.startswith('image/'): raise HTTPException(status_code=400, detail='Invalid file type') size = 0 async for chunk in file.file: size += len(chunk) if size > MAX_SIZE: raise HTTPException(status_code=400, detail='File too large') # reset file pointer if needed file.file.seek(0) # process file return {'message': 'File accepted'}
from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post('/upload') async def upload_file(file: UploadFile = File(...)): contents = await file.read() if len(contents) > 5_000_000: return {'error': 'File too large'} if not file.content_type.startswith('image/'): return {'error': 'Invalid file type'} # process file return {'message': 'File accepted'}
| Pattern | Memory Usage | Blocking Time | Responsiveness | Verdict |
|---|---|---|---|---|
| Read full file before validation | High (loads entire file) | Blocks event loop during read | Low (slow response for large files) | [X] Bad |
| Stream file and validate incrementally | Low (only chunks in memory) | Non-blocking with async iteration | High (fast rejection of invalid files) | [OK] Good |