Brainstorm's snippets (1/268)

  django-imagekit: Generate predictable filenames in cache


#  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 is:

# adapted from ""

from django.conf import settings
import os
from imagekit.utils import format_to_extension, suggest_extension

def my_get_hash(generator):
    name = ''
        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::


    will generate a name like this::


    where "/path/to/generated/images/" is the value specified by the

    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
        # 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,

    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)))