Лабораторная 4: S3-хранилище и вложения

This commit is contained in:
Алиса Шурман
2026-11-12 22:27:32 +03:00
parent ec540a1a72
commit 7fbdef3a6a
25 changed files with 1447 additions and 23 deletions
+38
View File
@@ -0,0 +1,38 @@
"""Image checks without network access."""
import warnings
from PIL import Image, UnidentifiedImageError
MAX_BYTES = 10_485_760
MAX_PIXELS = 40_000_000
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
class InvalidImage(ValueError):
pass
class TooManyPixels(ValueError):
pass
def validate_image(file, mime):
try:
with warnings.catch_warnings():
warnings.simplefilter('error', Image.DecompressionBombWarning)
file.seek(0)
with Image.open(file) as img:
if img.width * img.height > MAX_PIXELS:
raise TooManyPixels()
actual = {'PNG': 'image/png', 'JPEG': 'image/jpeg'}.get(img.format)
if actual != mime or actual is None:
raise InvalidImage()
if getattr(img, 'n_frames', 1) != 1:
raise InvalidImage()
img.verify()
file.seek(0)
with Image.open(file) as img:
img.load() # Detect truncated JPEG/pixel data, not only its header.
except (Image.DecompressionBombError, Image.DecompressionBombWarning) as exc:
raise TooManyPixels() from exc
except (UnidentifiedImageError, OSError, SyntaxError, ValueError) as exc:
if isinstance(exc, TooManyPixels):
raise
raise InvalidImage() from exc
finally:
file.seek(0)