Skip to content

Instantly share code, notes, and snippets.

@davelowe
Created February 8, 2012 17:38
Show Gist options
  • Save davelowe/1771538 to your computer and use it in GitHub Desktop.
Save davelowe/1771538 to your computer and use it in GitHub Desktop.
Custom imagekit cache backend
import os
from django.db.models.signals import pre_save
from celery.execute import send_task
class CustomCacheStateBackend(object):
def has_changed(self, file):
if hasattr(file.instance, "_image_changed"):
return file.instance._image_changed
return True
def is_invalid(self, file):
if not getattr(file, '_file', None):
# No file on object. Have to check storage.
return not file.storage.exists(file.name)
return False
def validate(self, file):
"""
Generates a new image by running the processors on the source file.
"""
if self.is_invalid(file):
content = file.generate()
if content:
file.storage.save(file.name, content)
def invalidate(self, file):
from myapp.models import SomeModel
if self.has_changed(file):
file.delete(save=False)
if isinstance(file.instance, SomeModel):
send_task("myapp.models.regenerate_spec_images", [file.instance.pk, ])
def clear(self, file):
file.delete(save=False)
def register_field(self, model_class, field, attname):
pre_save.connect(_pre_save_handler, sender=model_class)
def _pre_save_handler(sender, instance, **kwargs):
from myapp.models import SomeModel
if isinstance(instance, SomeModel):
obj = SomeModel.objects.get(pk=instance.pk)
if os.path.dirname(instance.image.path) != os.path.dirname(obj.image.path):
instance._image_changed = True
else:
instance._image_changed = False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment