Skip to content

Commit

Permalink
Refactor AssetPublicQRViewSet to Prefer qr_code_id Over Primary Key (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
Ashesh3 authored Oct 12, 2023
1 parent ab695cd commit 5dff7a0
Showing 1 changed file with 7 additions and 18 deletions.
25 changes: 7 additions & 18 deletions care/facility/api/viewsets/asset.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import uuid

from django.conf import settings
from django.core.cache import cache
from django.db.models import Exists, OuterRef, Q
Expand Down Expand Up @@ -192,24 +190,15 @@ class AssetPublicQRViewSet(GenericViewSet):
lookup_field = "qr_code_id"

def retrieve(self, request, *args, **kwargs):
is_uuid = True
try:
uuid.UUID(kwargs["qr_code_id"])
except ValueError:
# If the qr_code_id is not a UUID, then it is the pk of the asset
is_uuid = False
if not kwargs["qr_code_id"].isnumeric():
return Response(status=status.HTTP_404_NOT_FOUND)

key = "asset:qr:" + kwargs["qr_code_id"]
qr_code_id = kwargs["qr_code_id"]
key = "asset:qr:" + qr_code_id
hit = cache.get(key)
if not hit:
if is_uuid:
instance = self.get_object()
else:
instance = get_object_or_404(
self.get_queryset(), pk=kwargs["qr_code_id"]
)
instance = self.get_queryset().filter(qr_code_id=qr_code_id).first()
if not instance: # If the asset is not found, try to find it by pk
if not qr_code_id.isnumeric():
return Response(status=status.HTTP_404_NOT_FOUND)
instance = get_object_or_404(self.get_queryset(), pk=qr_code_id)
serializer = self.get_serializer(instance)
cache.set(key, serializer.data, 60 * 60 * 24)
return Response(serializer.data)
Expand Down

0 comments on commit 5dff7a0

Please sign in to comment.