Last active
June 3, 2019 14:21
-
-
Save jsocol/dab48c9c4ab6388190ab to your computer and use it in GitHub Desktop.
django caching pattern examples
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 django.core.cache import cache | |
| from django.db import models | |
| EMPTY = '-' # Not "None" | |
| class MyModel(models.Model): | |
| @classmethod | |
| def _cache_key(cls, key): | |
| return 'mymodel:{}'.format(key) | |
| @classmethod | |
| def get(cls, key): | |
| cache_key = cls._cache_key(key) | |
| obj = cache.get(cache_key) | |
| if obj == EMPTY: | |
| return None # or raise DoesNotExist | |
| if obj: | |
| return obj | |
| try: | |
| obj = cls.objects.get(pk=key) | |
| except cls.DoesNotExist: | |
| cache.add(cache_key, EMPTY) | |
| return None # or raise | |
| cache.add(cache_key, obj) | |
| return obj | |
| @classmethod | |
| def flush(cls, key): | |
| cache_key = cls._cache_key(key) | |
| cache.delete(cache_key) # Can also "delete_many" | |
| def save(self, *args, **kwargs): | |
| ret = super(MyModel, self).save(*args, **kwargs) | |
| self.flush(self.pk) | |
| return ret | |
| def delete(self, *args, **kwargs): | |
| ret = super(MyModel, self).delete(*args, **kwargs) | |
| self.flush(self.pk) | |
| return ret |
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
| MyModelOptions._get_cache_key(cls, mymodel) | |
| MyModelOptions.get(cls, mymodel) | |
| MyModelOptions.flush(cls, mymodel) | |
| MyModelOptions.save(self) (call flush) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment