Skip to main content
In this lesson we improve the image upload endpoint to validate and sanitize uploads so the app only accepts real images and returns a safe, processed image. The endpoint already handled uploads and compression; here we add stronger checks to prevent renamed executables or malformed data from being accepted and to ensure the processed output is a valid image before sending it back. What you’ll get
  • Robust server-side image validation using a layered approach (quick type checks + deep validation).
  • Single-pass reading of uploaded bytes to avoid repeated file seeks.
  • Re-encoding via OpenCV to control JPEG compression and then verifying the result with Pillow before returning it.
  • Clear error messages and appropriate HTTP status codes for failure modes.
Validation checklist
Install Pillow before running the updated code:
Complete implementation
Example request (curl)
Example request (Postman) Notes and recommendations
  • imghdr is a helpful quick check but not foolproof; Pillow’s Image.verify() provides stronger validation.
  • Read the raw upload bytes once and reuse them for all checks and decoding; this avoids extra seeks and keeps flow simple.
  • Decode and re-encode with OpenCV so you can apply compression control; always verify the processed image with Pillow to ensure you do not return malformed binary.
  • Re-encoding to JPEG will flatten animations and drop alpha channels — animated GIFs become a single frame and transparency is lost.
  • Use secure production deployment: the Flask built-in server is not intended for production. Consider a production WSGI server such as Gunicorn.
Do not use Flask’s development server for production workloads. Use a production WSGI server like gunicorn and follow best practices for HTTPS and request size limits.
Links and references This update hardens the upload route so it validates incoming images, sanitizes inputs, and only returns a verified, processed image to clients.

Watch Video