django-imagekit: Generate predictable filenames in cache ¶
file settings.py:
# # ImageKit # #IMAGEKIT_DEFAULT_CACHEFILE_STRATEGY = 'imagekit.cachefiles.strategies.Optimistic' # Generate predictable filenames in cache #IMAGEKIT_SPEC_CACHEFILE_NAMER = 'imagekit.cachefiles.namers.source_name_as_path' IMAGEKIT_SPEC_CACHEFILE_NAMER = 'main.imagekit_overrides.source_name_as_path'
where file main.imagekit_overrides.py is:
# adapted from "imagekit.cachefiles.namers.source_name_as_path.py" from django.conf import settings import os from imagekit.utils import format_to_extension, suggest_extension def my_get_hash(generator): name = '' try: processor = generator.processors[0] width = processor.width height = processor.height name = '%dx%d' % (width, height) except Exception as e: name = generator.get_hash() return name def source_name_as_path(generator): """ A namer that, given the following source file name:: photos/thumbnails/bulldog.jpg will generate a name like this:: /path/to/generated/images/photos/thumbnails/bulldog/5ff3233527c5ac3e4b596343b440ff67.jpg where "/path/to/generated/images/" is the value specified by the ``IMAGEKIT_CACHEFILE_DIR`` setting. """ source_filename = getattr(generator.source, 'name', None) if source_filename is None or os.path.isabs(source_filename): # Generally, we put the file right in the cache file directory. dir = settings.IMAGEKIT_CACHEFILE_DIR else: # For source files with relative names (like Django media files), # use the source's name to create the new filename. dir = os.path.join(settings.IMAGEKIT_CACHEFILE_DIR, os.path.splitext(source_filename)[0]) ext = suggest_extension(source_filename or '', generator.format) #return os.path.normpath(os.path.join(dir, '%s%s' % (generator.get_hash(), ext))) return os.path.normpath(os.path.join(dir, '%s%s' % (my_get_hash(generator), ext)))