Check if sorl thumbnail has already cached an image using the low level API

允我心安 提交于 2019-12-12 06:45:16

问题


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:


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.



来源:https://stackoverflow.com/questions/20723599/check-if-sorl-thumbnail-has-already-cached-an-image-using-the-low-level-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!