55 lines
1.7 KiB
Python
55 lines
1.7 KiB
Python
"""Shared upload/remove logic for models holding one watermarked image
|
|
(columns image_original_path / image_watermarked_path / image_thumbnail_path)."""
|
|
|
|
from fastapi import HTTPException, UploadFile, status
|
|
from fastapi.concurrency import run_in_threadpool
|
|
|
|
from app.services.image_processing import (
|
|
ImageValidationError,
|
|
WatermarkUnavailableError,
|
|
delete_media_files,
|
|
load_logo,
|
|
process_image,
|
|
read_upload,
|
|
)
|
|
|
|
_COLS = ("image_original_path", "image_watermarked_path", "image_thumbnail_path")
|
|
|
|
|
|
async def replace_image(db, obj, file: UploadFile) -> None:
|
|
try:
|
|
load_logo()
|
|
except WatermarkUnavailableError as exc:
|
|
raise HTTPException(status.HTTP_503_SERVICE_UNAVAILABLE, str(exc)) from None
|
|
try:
|
|
validated = await read_upload(file)
|
|
except ImageValidationError as exc:
|
|
raise HTTPException(exc.status_code, {"errors": [exc.message]}) from None
|
|
|
|
stored = await run_in_threadpool(process_image, validated)
|
|
old = tuple(getattr(obj, c) for c in _COLS)
|
|
obj.image_original_path = stored.original_path
|
|
obj.image_watermarked_path = stored.watermarked_path
|
|
obj.image_thumbnail_path = stored.thumbnail_path
|
|
try:
|
|
await db.commit()
|
|
except Exception:
|
|
await db.rollback()
|
|
delete_media_files(stored.original_path, stored.watermarked_path, stored.thumbnail_path)
|
|
raise
|
|
delete_media_files(*old)
|
|
await db.refresh(obj)
|
|
|
|
|
|
async def remove_image(db, obj) -> None:
|
|
old = tuple(getattr(obj, c) for c in _COLS)
|
|
for c in _COLS:
|
|
setattr(obj, c, None)
|
|
await db.commit()
|
|
delete_media_files(*old)
|
|
await db.refresh(obj)
|
|
|
|
|
|
def image_files(obj) -> tuple:
|
|
return tuple(getattr(obj, c) for c in _COLS)
|