Performance: File validation (size, type)
This affects page load speed and interaction responsiveness by preventing large or invalid files from being processed or uploaded.
Jump into concepts and practice - no test required
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 |
from fastapi import FastAPI, File, UploadFile, HTTPException
app = FastAPI()
@app.post('/upload')
async def upload(file: UploadFile = File(...)):
if file.content_type not in ['image/png', 'image/jpeg']:
raise HTTPException(status_code=400, detail='Invalid file type')
contents = await file.read()
if len(contents) > 2_000_000:
raise HTTPException(status_code=400, detail='File too large')
return {'filename': file.filename, 'size': len(contents)}from fastapi import FastAPI, File, UploadFile, HTTPException
app = FastAPI()
@app.post('/upload')
async def upload(file: UploadFile = File(...)):
if file.content_type != 'image/png' or file.content_type != 'image/jpeg':
raise HTTPException(status_code=400, detail='Invalid file type')
contents = await file.read()
if len(contents) > 1_000_000:
raise HTTPException(status_code=400, detail='File too large')
return {'filename': file.filename}