feat: adjusted user cache data to match the Serializer structure

This commit is contained in:
Chneemann 2025-03-25 09:47:02 +01:00
parent 20015dab98
commit 367b8a3914
3 changed files with 15 additions and 16 deletions

View file

@ -2,27 +2,25 @@ import json
from django.core.cache import cache from django.core.cache import cache
from .models import User from .models import User
from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import ObjectDoesNotExist
from django.core import serializers from .serializers import UserSerializer
def get_cached_user(user_id): def get_cached_user(user_id):
cache_key = f"user_{user_id}" cache_key = f"user_{user_id}"
cached_user_json = cache.get(cache_key) cached_user = cache.get(cache_key)
if cached_user_json is not None:
return json.loads(cached_user_json)
if cached_user is not None:
return cached_user
try: try:
user = User.objects.get(id=user_id) user = User.objects.get(id=user_id)
except ObjectDoesNotExist: except ObjectDoesNotExist:
return None return None
if user: serializer = UserSerializer(user)
user_data = serializers.serialize('json', [user]) user_data = serializer.data
cache.set(cache_key, user_data, timeout=3600) cache.set(cache_key, user_data, timeout=3600)
return json.loads(user_data)[0]['fields'] return user_data
else:
return None
def cache_user(user_id, user_data, timeout=3600): def cache_user(user_id, user_data, timeout=3600):
@ -30,5 +28,4 @@ def cache_user(user_id, user_data, timeout=3600):
Saves user data in the cache. Saves user data in the cache.
""" """
cache_key = f"user_{user_id}" cache_key = f"user_{user_id}"
user_json = json.dumps(user_data) cache.set(cache_key, user_data, timeout)
cache.set(cache_key, user_json, timeout)

View file

@ -11,5 +11,6 @@ class UserSerializer(serializers.ModelSerializer):
class UserViewSet(viewsets.ModelViewSet): class UserViewSet(viewsets.ModelViewSet):
serializer_class = UserSerializer serializer_class = UserSerializer
queryset = User.objects.all() queryset = User.objects.all()
parser_classes = [CamelCaseJSONParser] parser_classes = [CamelCaseJSONParser]
renderer_classes = [CamelCaseJSONRenderer] renderer_classes = [CamelCaseJSONRenderer]

View file

@ -17,6 +17,7 @@ class UserViewSet(viewsets.ModelViewSet):
user = self.get_object() user = self.get_object()
serialized_user = UserSerializer(user).data serialized_user = UserSerializer(user).data
cache_user(user_id, serialized_user) cache_user(user_id, serialized_user)
return Response(serialized_user) return Response(serialized_user)