Skip to content

Commit

Permalink
Generate avif thumbnails async in task
Browse files Browse the repository at this point in the history
  • Loading branch information
stefanw committed Oct 18, 2023
1 parent 5377c5f commit 8cff2c3
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 23 deletions.
28 changes: 5 additions & 23 deletions fragdenstaat_de/fds_cms/apps.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,5 @@
import logging
from io import BytesIO

from django.apps import AppConfig
from django.conf import settings
from django.core.files.base import ContentFile

from PIL import Image

try:
import pillow_avif # noqa
except ImportError:
pillow_avif = None

logger = logging.getLogger(__name__)


class FdsCmsConfig(AppConfig):
Expand All @@ -26,7 +13,7 @@ def ready(self):

account_merged.connect(merge_user)

if pillow_avif is not None and settings.FDS_THUMBNAIL_ENABLE_AVIF:
if settings.FDS_THUMBNAIL_ENABLE_AVIF:
from easy_thumbnails.signals import thumbnail_created

thumbnail_created.connect(store_as_avif)
Expand All @@ -41,12 +28,7 @@ def merge_user(sender, old_user=None, new_user=None, **kwargs):
def store_as_avif(sender, **kwargs):
if not sender.name.endswith((".png", ".jpg", ".jpeg")):
return
logger.info("Converting %s to avif", sender.name)
avif_name = ".".join([sender.name, "avif"])
img_file = sender.storage.open(sender.name, "rb")
im = Image.open(img_file)
out_file = BytesIO()
im.save(out_file, format="avif", quality=80)
out_file.seek(0)
sender.storage.save(avif_name, ContentFile(out_file.read()))
logger.info("Done converting %s to avif", sender.name)

from .tasks import generate_avif_thumbnail

generate_avif_thumbnail.delay(sender.name, sender.storage)
28 changes: 28 additions & 0 deletions fragdenstaat_de/fds_cms/tasks.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,37 @@
import logging
from io import BytesIO

from django.core.files.base import ContentFile

from celery import shared_task
from easy_thumbnails.files import generate_all_aliases
from PIL import Image

try:
import pillow_avif # noqa
except ImportError:
pillow_avif = None

logger = logging.getLogger(__name__)


@shared_task
def generate_thumbnails(model, pk, field):
instance = model._default_manager.get(pk=pk)
fieldfile = getattr(instance, field)
generate_all_aliases(fieldfile, include_global=True)


@shared_task
def generate_avif_thumbnail(filepath: str, storage):
if pillow_avif is None:
return
logger.info("Converting %s to avif", filepath)
avif_path = storage.path(".".join([filepath, "avif"]))
img_file = storage.open(filepath, "rb")
im = Image.open(img_file)
out_file = BytesIO()
im.save(out_file, format="avif", quality=80)
out_file.seek(0)
storage.save(avif_path, ContentFile(out_file.read()))
logger.info("Done converting %s to avif", filepath)

0 comments on commit 8cff2c3

Please sign in to comment.