forked from mtusi2026/mtusi2026lab4
feat: add s3 client and image validation utils
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
import io
|
||||
from PIL import Image
|
||||
from fastapi import HTTPException
|
||||
|
||||
MAX_SIZE = 10 * 1024 * 1024 # 10 мбайт
|
||||
MAX_PIXELS = 40_000_000
|
||||
|
||||
def validate_image(content: bytes) -> str:
|
||||
if len(content) > MAX_SIZE:
|
||||
raise HTTPException(413, "File too large")
|
||||
try:
|
||||
img = Image.open(io.BytesIO(content))
|
||||
img.verify()
|
||||
img = Image.open(io.BytesIO(content))
|
||||
except Exception:
|
||||
raise HTTPException(415, "Invalid image format")
|
||||
|
||||
if img.format not in ("PNG", "JPEG"):
|
||||
raise HTTPException(415, "Unsupported media type")
|
||||
|
||||
width, height = img.size
|
||||
if width * height > MAX_PIXELS:
|
||||
raise HTTPException(413, "Image too large in pixels")
|
||||
|
||||
return "image/png" if img.format == "PNG" else "image/jpeg"
|
||||
@@ -0,0 +1,20 @@
|
||||
import boto3
|
||||
from botocore.client import Config
|
||||
import os
|
||||
|
||||
s3 = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=os.getenv("S3_ENDPOINT", "http://minio:9000"),
|
||||
aws_access_key_id=os.getenv("S3_ACCESS_KEY", "minioadmin"),
|
||||
aws_secret_access_key=os.getenv("S3_SECRET_KEY", "minioadmin"),
|
||||
config=Config(signature_version="s3v4"),
|
||||
region_name="us-east-1",
|
||||
)
|
||||
|
||||
BUCKET = os.getenv("S3_BUCKET", "attachments")
|
||||
|
||||
def ensure_bucket():
|
||||
try:
|
||||
s3.head_bucket(Bucket=BUCKET)
|
||||
except Exception:
|
||||
s3.create_bucket(Bucket=BUCKET)
|
||||
Reference in New Issue
Block a user