import io import hashlib from django.db import transaction from celery import shared_task from celery.exceptions import Retry from PIL import Image as PillowImage import blurhash from .models import PostFileModel @shared_task(autoretry_for=(Exception,), retry_backoff=True, max_retries=5) def generate_blur_hash_PostFile(file_id): try: with transaction.atomic(): img = PostFileModel.objects.select_for_update().get(id=file_id) image_data = io.BytesIO(img.file.read()) pil_img = PillowImage.open(image_data) blurhash_string = blurhash.encode(pil_img, 4, 3) img.refresh_from_db() img.blur_hash = blurhash_string img.save() return f"Successfully generated blur hash for file {file_id}" # Success message except Exception as e: error_message = f"Error generating blur hash for file {file_id}: {e}" print(error_message) raise Retry(exc=e) # Retry on exception return error_message # This ensures the error message is stored in the results @shared_task(autoretry_for=(Exception,), retry_backoff=True, max_retries=5) def generate_md5_hash_PostFile(file_id): try: with transaction.atomic(): pstfile = PostFileModel.objects.select_for_update().get(id=file_id) hash_md5 = hashlib.md5() with open(pstfile.file.path, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) md5_hash = hash_md5.hexdigest() pstfile.refresh_from_db() pstfile.hash_md5 = md5_hash pstfile.save() return f"Successfully generated MD5 hash for file {file_id}" # Success message except Exception as e: error_message = f"Error generating MD5 hash for file {file_id}: {e}" print(error_message) raise Retry(exc=e) # Retry on exception return error_message # This ensures the error message is stored in the results