From 4eb22bd0b8a735c5127830028803fc126040482f Mon Sep 17 00:00:00 2001 From: Aroy-Art Date: Sat, 1 Feb 2025 22:54:25 +0100 Subject: [PATCH] Add: task for generating md5 & blur hashes --- backend/apps/files/tasks.py | 54 +++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 backend/apps/files/tasks.py diff --git a/backend/apps/files/tasks.py b/backend/apps/files/tasks.py new file mode 100644 index 0000000..d0e23d8 --- /dev/null +++ b/backend/apps/files/tasks.py @@ -0,0 +1,54 @@ +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