Skip to content

Commit

Permalink
optimisation: Barrier Detail cache (#850)
Browse files Browse the repository at this point in the history
* optimisation: Barrier Detail cache

---------

Co-authored-by: abarolo <[email protected]>
Co-authored-by: Uka Osim <[email protected]>
  • Loading branch information
3 people authored Aug 2, 2024
1 parent 2f95f87 commit 0cb2bbe
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 8 deletions.
15 changes: 15 additions & 0 deletions api/barriers/barrier_cache.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from django.core.cache import cache

BARRIERS_PREFIX = "barriers/"


def get(pk):
return cache.get(f"{BARRIERS_PREFIX}/{pk}")


def delete(pk):
cache.delete(f"{BARRIERS_PREFIX}/{pk}")


def set(pk, obj):
cache.set(f"{BARRIERS_PREFIX}/{pk}", obj, 120)
68 changes: 61 additions & 7 deletions api/barriers/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

from dateutil.parser import parse
from django.db import transaction
from django.db.models import Case, CharField, F, Value, When
from django.db.models import Case, CharField, F, Prefetch, Value, When
from django.http import StreamingHttpResponse
from django.shortcuts import get_object_or_404
from django.utils import timezone
Expand All @@ -18,6 +18,7 @@
from rest_framework.viewsets import GenericViewSet, ModelViewSet
from simple_history.utils import bulk_create_with_history

from api.barriers import barrier_cache
from api.barriers.exceptions import PublicBarrierPublishException
from api.barriers.helpers import get_or_create_public_barrier
from api.barriers.models import (
Expand Down Expand Up @@ -266,9 +267,7 @@ class BarrierList(generics.ListAPIView):
Barrier.barriers.all()
.select_related("priority")
.prefetch_related(
"tags",
"organisations",
"progress_updates",
"tags", "organisations", "progress_updates", "valuation_assessments"
)
)
serializer_class = BarrierListSerializer
Expand Down Expand Up @@ -422,14 +421,44 @@ class BarrierDetail(TeamMemberModelMixin, generics.RetrieveUpdateAPIView):
lookup_field = "pk"
queryset = (
Barrier.barriers.all()
.select_related("priority")
.select_related(
"priority",
"created_by",
"modified_by",
"proposed_estimated_resolution_date_user",
)
.prefetch_related(
"tags",
Prefetch(
"barrier_team",
queryset=TeamMember.objects.select_related("user")
.filter(role="Owner")
.all(),
),
"organisations",
Prefetch(
"progress_updates",
queryset=BarrierProgressUpdate.objects.order_by("-created_on").all(),
),
Prefetch(
"programme_fund_progress_updates",
queryset=ProgrammeFundProgressUpdate.objects.select_related(
"created_by", "modified_by"
)
.order_by("-created_on")
.all(),
),
"barrier_commodities",
"public_barrier",
"categories",
"economic_assessments",
"valuation_assessments",
"organisations",
"tags",
Prefetch(
"next_steps_items",
queryset=BarrierNextStepItem.objects.filter(
status="IN_PROGRESS"
).order_by("-completion_date"),
),
)
)

Expand All @@ -447,6 +476,10 @@ def perform_update(self, serializer):
self.update_contributors(barrier)
barrier = serializer.save(modified_by=self.request.user)
self.update_metadata_for_proposed_estimated_date(barrier)
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
pk = self.kwargs[lookup_url_kwarg]

barrier_cache.delete(pk)

def update_metadata_for_proposed_estimated_date(self, barrier):
# get patched data from request
Expand All @@ -458,6 +491,24 @@ def update_metadata_for_proposed_estimated_date(self, barrier):
barrier.proposed_estimated_resolution_date_created = datetime.now()
barrier.save()

def retrieve(self, request, *args, **kwargs):
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
try:
pk = self.kwargs[lookup_url_kwarg]
except KeyError:
"""If view with `code` lookup (throws KeyError), don't cache"""
return super().retrieve(request, *args, **kwargs)

data = barrier_cache.get(pk)
if data:
return Response(data)

response = super().retrieve(request, *args, **kwargs)

barrier_cache.set(pk, response.data)

return response


class BarrierFullHistory(generics.GenericAPIView):
"""
Expand Down Expand Up @@ -885,6 +936,9 @@ def create(self, request, *args, **kwargs):
serializer.is_valid(raise_exception=True)
self.perform_create(serializer, request.user)
headers = self.get_success_headers(serializer.data)

barrier_cache.delete(serializer.data["barrier"])

return Response(
serializer.data, status=status.HTTP_201_CREATED, headers=headers
)
Expand Down
2 changes: 1 addition & 1 deletion api/metadata/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ def get_trading_bloc_overseas_regions(trading_bloc_code):

def get_wto_committee_groups():
committee_groups = []
for group in wto_models.WTOCommitteeGroup.objects.all():
for group in wto_models.WTOCommitteeGroup.objects.prefetch_related("committees"):
committee_groups.append(
{
"id": str(group.id),
Expand Down

0 comments on commit 0cb2bbe

Please sign in to comment.