From 50606745f497625cece4afef2adee300ebafee1a Mon Sep 17 00:00:00 2001 From: Abderrahmane Smimite Date: Sat, 21 Sep 2024 13:28:08 +0200 Subject: [PATCH] local approach for cache invalidation --- backend/core/views.py | 32 +++++++++++++++++++++++++------- 1 file changed, 25 insertions(+), 7 deletions(-) diff --git a/backend/core/views.py b/backend/core/views.py index f66286f74..0e355a3b9 100644 --- a/backend/core/views.py +++ b/backend/core/views.py @@ -133,24 +133,18 @@ def _process_request_data(self, request: Request) -> None: def create(self, request: Request, *args, **kwargs) -> Response: self._process_request_data(request) - cache.clear() return super().create(request, *args, **kwargs) def update(self, request: Request, *args, **kwargs) -> Response: self._process_request_data(request) - cache.clear() return super().update(request, *args, **kwargs) def partial_update(self, request: Request, *args, **kwargs) -> Response: self._process_request_data(request) - cache.clear() return super().partial_update(request, *args, **kwargs) def destroy(self, request: Request, *args, **kwargs) -> Response: - """ - Invalidate cache when an object is deleted. - """ - cache.clear() # Clear cache after deletion + self._process_request_data(request) return super().destroy(request, *args, **kwargs) class Meta: @@ -268,6 +262,30 @@ class ThreatViewSet(BaseModelViewSet): filterset_fields = ["folder", "risk_scenarios"] search_fields = ["name", "provider", "description"] + def perform_create(self, serializer): + """ + Invalidate cache when a new threat is created. + """ + serializer.save() + # Invalidate the list and threats_count caches after creating a new threat + cache.clear() + + def perform_update(self, serializer): + """ + Invalidate cache when a threat is updated. + """ + serializer.save() + # Invalidate the cache for the updated threat and the list view + cache.clear() + + def perform_destroy(self, instance): + """ + Invalidate cache when a threat is deleted. + """ + super().perform_destroy(instance) + # Invalidate the cache for the deleted threat and the list view + cache.clear() + @method_decorator(cache_page(60 * MED_CACHE_TTL)) @method_decorator(vary_on_cookie) def list(self, request, *args, **kwargs):