From 00b4388245f7777276af351e3afd68af2417c426 Mon Sep 17 00:00:00 2001 From: Matthew Dapena-Tretter Date: Tue, 23 Sep 2014 18:35:38 -0400 Subject: [PATCH] Support should_verify_existence on strategies MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This prevents extra IO. Different defaults are used for async backends since we can’t assume that `existence_required` resulted in existence synchronously. --- imagekit/cachefiles/__init__.py | 9 ++++++++- imagekit/cachefiles/backends.py | 2 ++ imagekit/cachefiles/strategies.py | 3 +++ tests/utils.py | 2 ++ 4 files changed, 15 insertions(+), 1 deletion(-) diff --git a/imagekit/cachefiles/__init__.py b/imagekit/cachefiles/__init__.py index 34892ec..2ba5cb8 100644 --- a/imagekit/cachefiles/__init__.py +++ b/imagekit/cachefiles/__init__.py @@ -128,7 +128,14 @@ class ImageCacheFile(BaseIKFile, ImageFile): # Dispatch the existence_required signal before checking to see if the # file exists. This gives the strategy a chance to create the file. existence_required.send(sender=self, file=self) - return self.cachefile_backend.exists(self) + + try: + check = self.cachefile_strategy.should_verify_existence(self) + except AttributeError: + # All synchronous backends should have created the file as part of + # `existence_required` if they wanted to. + check = getattr(self.cachefile_backend, 'is_async', False) + return self.cachefile_backend.exists(self) if check else True def __getstate__(self): state = copy(self.__dict__) diff --git a/imagekit/cachefiles/backends.py b/imagekit/cachefiles/backends.py index 25ce43f..1512f51 100644 --- a/imagekit/cachefiles/backends.py +++ b/imagekit/cachefiles/backends.py @@ -121,6 +121,8 @@ class BaseAsync(Simple): """ Base class for cache file backends that generate files asynchronously. """ + is_async = True + def generate(self, file, force=False): # Schedule the file for generation, unless we know for sure we don't # need to. If an already-generated file sneaks through, that's okay; diff --git a/imagekit/cachefiles/strategies.py b/imagekit/cachefiles/strategies.py index 98f712e..bcd8211 100644 --- a/imagekit/cachefiles/strategies.py +++ b/imagekit/cachefiles/strategies.py @@ -29,6 +29,9 @@ class Optimistic(object): def on_source_saved(self, file): file.generate() + def should_verify_existence(self, file): + return False + class DictStrategy(object): def __init__(self, callbacks): diff --git a/tests/utils.py b/tests/utils.py index 5a9f1c5..b6c4952 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -77,5 +77,7 @@ class DummyAsyncCacheFileBackend(Simple): A cache file backend meant to simulate async generation. """ + is_async = True + def generate(self, file, force=False): pass