Check if sorl thumbnail has already cached an imag

2019-08-20 17:46发布

Sorl thumbnail has a low-level API that allows you to do, for example:

from sorl.thumbnail import get_thumbnail
im = get_thumbnail(my_file, '100x100', crop='center', quality=99)

This returns a reference to the cached file. If it's already been created, it's super quick. However, if it has to create it for the first time it can take a long time when using remote storage such as S3.

Is there a way to run a command in Python (ie. not in a template) to check if sorl will have to generate a thumbnail for the first time?

PS. I'm aware of similar question here but this is asking about it in a template context, and has a hacky solution as an answer that uses custom SQL and not the sorl API.

1条回答
地球回转人心会变
2楼-- · 2019-08-20 18:27

In my version sorl.thumbnail, 11.12, the method get_thumbnail is defined in sorl.thumbnail.base.py and starts as follows:

def get_thumbnail(self, file_, geometry_string, **options):
    """..."""
    source = ImageFile(file_)
    for key, value in self.default_options.iteritems():
        options.setdefault(key, value)
    # ...
    for key, attr in self.extra_options:
        value = getattr(settings, attr)
        if value != getattr(default_settings, attr):
            options.setdefault(key, value)
    name = self._get_thumbnail_filename(source, geometry_string, options)
    thumbnail = ImageFile(name, default.storage)
    cached = default.kvstore.get(thumbnail)
    if cached:
        return cached
    if not thumbnail.exists():
        ...

If you use this code and return something like

cached or thumbnail.exists()

this should give you the desired result.

查看更多
登录 后发表回答