Package: django-sage-cache
Django Sage CacheWhat is django-sage-cache package?django-sage-cache is a great package for caching data in the Django framework. In this package, an attempt has been made to use both private and shared caching techniques. Note that data caching is done at the database level. This is to reduce the number of queries to the database. The database we used to cache the data in this framework is called Redis.What is HTTP caching?Caching is a technique that stores a copy of a given resource and serves it back when requested. When a web cache has a requested resource in its store, it intercepts the request and returns its copy instead of re-downloading from the originating server. This achieves several goals: it eases the server's load that doesn’t need to serve all clients itself, and it improves performance by being closer to the client, i.e., it takes less time to transmit the resource back.What is Redis?Redis is an in-memory data structure store, used as a distributed, in-memory key-value database, cache, and message broker, with optional durability.The Latest version ofdjango-sage-cachedocumentationProject DetailGit RulesGet StartedUsageFilter BackendsSignalsCache MethodsSettingsProject DetailLanguage: Python > 3.5Framework: Django > 3.1Git RulesS.A.G.E. team Git Rules Policy is available here:S.A.G.E. Git PolicyGetting StartedFirst install the package using pip:$pipinstalldjango-sage-cacheThen addsage_cacheto INSTALLED_APPS:INSTALLED_APPS=[...'sage_cache',...]For using cache support you need to configredis server:ubuntu:$sudoaptinstallredis-serverwindows:you can download redis server from hereThen add redis cache to django settings:CACHES={"default":{"BACKEND":"django_redis.cache.RedisCache","LOCATION":'redis://localhost:6379'}}UsageThere are multiple ways to usesage_cachein your project:For simple usage you can use Model Mixin:# models.pyfromsage_cache.mixins.model_cacheimportModelCacheMixinclassCategory(models.Model,ModelCacheMixin):CACHE_KEY='category'# set for cache (set cache with this key)title=models.CharField(max_length=255)created=models.DateTimeField(auto_now_add=True)modified=models.DateTimeField(auto_now=True)# views.pyclassCategoryViewset(ModelViewSet):serializer_class=CategorySerializermodel_class=Category# set for cache (its your model)defget_queryset(self):returnself.model_class.get_all_from_cache()# get from cache instead of dbUse built-in decorators:You can use built-in view decorators in DRF methodsfromrest_framework.responseimportResponsefromrest_framework.viewsetsimportModelViewSetfromsage_cache.decorators.cache_querysetimportcache_queryset_per_siteclassCategoryViewset(ModelViewSet):serializer_class=CategorySerializerqueryset=Category.objects.all()model_class=Category# set for cache@cache_queryset_per_site()# set for cache (per site caching)deflist(self,request,*args,**kwargs):queryset=self.filter_queryset(self.get_queryset())page=self.paginate_queryset(queryset)ifpageisnotNone:serializer=self.get_serializer(page,many=True)returnself.get_paginated_response(serializer.data)serializer=self.get_serializer(queryset,many=True)returnResponse(serializer.data)list of built-in decorators:cache_queryset_per_sitecache_queryset_per_usercache_page_per_sitecache_page_per_userYou can also write your own functions:sage_cacheprovides some useful functions and tools for cache support, You can use them to create cache appslist of tools you can access:services:cache_funcs:get_all_from_cachefilter_from_cachefilter_related_from_cacheclear_cache_for_usersclear_cache_for_modelclear_model_cache_for_usertimeout_funcs:get_timeout_for_userdefault_timeoutview_funcs:get_objectFilter BackendIn cached views use these Filter/Search backends:CacheFilterBackendCacheSearchBackendfromrest_framework.responseimportResponsefromrest_framework.viewsetsimportModelViewSetfromsage_cache.decorators.cache_querysetimportcache_queryset_per_sitefromsage_cache.filters.backendimportCacheFilterBackend,CacheSearchBackendclassCategoryViewset(ModelViewSet):serializer_class=CategorySerializerqueryset=Category.objects.all()model_class=Category# set for cachefilter_backends=(CacheFilterBackend,CacheSearchBackend)# cache backends@cache_queryset_per_site()# set for cache (per site caching)deflist(self,request,*args,**kwargs):queryset=self.filter_queryset(self.get_queryset())page=self.paginate_queryset(queryset)ifpageisnotNone:serializer=self.get_serializer(page,many=True)returnself.get_paginated_response(serializer.data)serializer=self.get_serializer(queryset,many=True)returnResponse(serializer.data)SignalsWhen you set cache it will not update until timeout and expiration, In some situations you need to update cache when your data is updated in main db, For this reason we use Signals to update/remove cache.A simple example of update cache signalfromsage_cache.services.cache_funcsimportclear_cache_for_model@receiver(post_save,sender=Category)defupdate_category(sender,instance,created,**kwargs):clear_cache_for_model(sender.CACHE_KEY)# remove all cache for updated modelList of some useful functions for Cache Updating:clear_cache_for_usersclear_cache_for_modelclear_model_cache_for_userCache MethodsYou can cache your project in 2 ways:per siteper userIn per site mode you set just 1 cache key for each model in redis, And it is same for all users, But in per user method each user has unique cache keys.For example cache key forCategorymodel:mode (per site): ":category"mode (per user): ":category-mrhnz13@gmail.com"In per user mode you can set multiple timeouts for each user.SettingsCACHE_QUERYSET_ENABLED=True# Is cache queryset enabledCACHE_PAGE_ENABLED=True# Is cache page enabledCACHE_TIMEOUT=60# cache default timeout in secondsCACHE_PER_USER_UNIQUE_ATTR='username'# unique field in UserCACHE_PER_USER_TIMEOUT_FUNC='sage_cache.services.timeout_funcs.default_timeout'# in per_user mode timeout will calculate by this functionCACHE_PAGE_PER_SITE_PREFIX='sage_cache_site'# cache page key prefixTeamSepehr Akbarazadeh MaintainerMehran Rahmanzadeh Maintainer