matthewwithanm / django-imagekit

Automated image processing for Django. Currently v4.0
http://django-imagekit.rtfd.org/
BSD 3-Clause "New" or "Revised" License
2.26k stars 276 forks source link

How to delete thumbnail after the source image got deleted ? #522

Closed TonyXdZ closed 3 years ago

vstoykov commented 3 years ago

You can clear all thumbnails in the CACHE directory. They will be regenerated when needed. This may not be convenient in all situations (like if you have many many images).

If you already deleted the files and want to cleanup stale thumbnails without regenerating the valid ones it will be more tricky.

I'm not sure what is your exact use case though.

pickfire commented 3 years ago

How to do it without clearing all thumbnails?

TonyXdZ commented 3 years ago

@vstoykov thanks for your solution but in my case thumbnails wont be generated again because im using the "Optimistic" cachefile strategy, meaning the thumbnail is created only when the source image is created or changed... so clearing the CACHE dir will not fix it.

q0w commented 3 years ago

@TonyXdZ @pickfire you can use django-cleanup signals

#tasks.py

import dramatiq
from imagekit.cachefiles import LazyImageCacheFile
from imagekit.utils import get_cache

@dramatiq.actor
def _clear_cache_image(source_file):
    thumbnail = LazyImageCacheFile("users:user:photo_thumbnail", source=source_file)
    cache_backend = thumbnail.cachefile_backend
    get_cache().delete(cache_backend.get_key(thumbnail))
    thumbnail.storage.delete(thumbnail.name)

#signals.py

from django_cleanup.signals import cleanup_pre_delete

@receiver(cleanup_pre_delete)
def clear_cache_image(**kwargs):
    _clear_cache_image.send(kwargs["file"])
pickfire commented 3 years ago

Thanks a lot, that works like a charm. I didn't dig into the source code of imagekit to see how this can be done, get_cache is not documented so I didn't saw that.

TonyXdZ commented 3 years ago

@q0w thank you so much it's working ( after i made some changes because i have implemented my own cache file cleaner already )