Created
          March 8, 2012 15:10 
        
      - 
      
- 
        Save bruth/2001429 to your computer and use it in GitHub Desktop. 
    ETag "ready" Django model using a modified datetime
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 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