Skip to content

Instantly share code, notes, and snippets.

@bruth
Created March 8, 2012 15:10
Show Gist options
  • Save bruth/2001429 to your computer and use it in GitHub Desktop.
Save bruth/2001429 to your computer and use it in GitHub Desktop.
ETag "ready" Django model using a modified datetime
from datetime import datetime
from django.db import models
from django.core.cache import cache
class ModifiedModel(models.Model):
modified = models.DateTimeField()
class Meta(object):
abstract = True
def save(self, *args, **kwargs):
etag = self.invalidate_cache()
last_modified = self.modified
self.modified = datetime.now()
try:
super(ModifiedModel, self).save(*args, **kwargs)
except Exception, e:
# Revert if the save failed
self.modified = last_modified
cache.set(etag, 1)
raise e
def invalidate_cache(self):
etag = self.generate_etag()
cache.delete(etag)
return etag
def generate_etag(self):
kwargs = {
'app': self._meta.app_label,
'model': self._meta.module_name,
'id': self.id,
'version': self.modified.isoformat(),
}
return '{app}.{model}-{id},{version}'.format(**kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment