From 61ab0d9bbb8b209723e75fda9aae8e62690d6cbc Mon Sep 17 00:00:00 2001 From: Chneemann Date: Tue, 25 Mar 2025 08:40:36 +0100 Subject: [PATCH] feat: implemented Redis caching for user data --- user_app/caching.py | 11 ++++++++++- user_app/views.py | 17 ++++++++++++++++- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/user_app/caching.py b/user_app/caching.py index 73fd48a..1cefd41 100644 --- a/user_app/caching.py +++ b/user_app/caching.py @@ -21,4 +21,13 @@ def get_cached_user(user_id): cache.set(cache_key, user_data, timeout=3600) return json.loads(user_data)[0]['fields'] else: - return None \ No newline at end of file + return None + + +def cache_user(user_id, user_data, timeout=3600): + """ + Saves user data in the cache. + """ + cache_key = f"user_{user_id}" + user_json = json.dumps(user_data) + cache.set(cache_key, user_json, timeout) \ No newline at end of file diff --git a/user_app/views.py b/user_app/views.py index 258bd06..2bb34b9 100644 --- a/user_app/views.py +++ b/user_app/views.py @@ -1,7 +1,22 @@ from rest_framework import viewsets +from rest_framework.response import Response from .models import User from .serializers import UserSerializer +from .caching import get_cached_user, cache_user class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() - serializer_class = UserSerializer \ No newline at end of file + serializer_class = UserSerializer + + def retrieve(self, request, *args, **kwargs): + user_id = kwargs.get("pk") + cached_user = get_cached_user(user_id) + + if cached_user: + return Response(cached_user) + + user = self.get_object() + serialized_user = UserSerializer(user).data + cache_user(user_id, serialized_user) + + return Response(serialized_user) \ No newline at end of file