An AI-generated FastAPI endpoint handles avatar uploads for a user profile service.
Python backend with FastAPI, running behind nginx with a 10MB client body limit.
Select suspicious lines in the terminal to flag them before submitting your verdict.
from fastapi import APIRouter, UploadFile, File, HTTPException
from uuid import uuid4
import imghdr
import os
router = APIRouter()
ALLOWED_EXTENSIONS = {"png", "jpg", "jpeg", "webp"}
MAX_SIZE = 5 * 1024 * 1024
@router.post("/users/me/avatar")
async def upload_avatar(file: UploadFile = File(...)):
ext = os.path.splitext(file.filename)[1].lstrip(".").lower()
if ext not in ALLOWED_EXTENSIONS:
raise HTTPException(400, "Invalid file type")
contents = await file.read()
if len(contents) > MAX_SIZE:
raise HTTPException(400, "File too large")
if imghdr.what(None, contents) not in ALLOWED_EXTENSIONS:
raise HTTPException(400, "Content does not match extension")
safe_name = f"avatar_{uuid4().hex}.{ext}"
with open(f"/var/uploads/{safe_name}", "wb") as f:
f.write(contents)
return {"filename": safe_name}