Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sprint 63 - T-Regz and TRUST - 2 #855

Merged
merged 3 commits into from
Aug 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
4 changes: 2 additions & 2 deletions api/barriers/serializers/data_workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -471,12 +471,12 @@ def get_date_estimated_resolution_date_first_added(self, instance):
estimated_resolution_date__isnull=False
).order_by("history_date")

first = history.values("estimated_resolution_date").first()
first = history.values("history_date").first()

if not first:
return

return first["estimated_resolution_date"].strftime("%Y-%m-%d")
return first["history_date"].strftime("%Y-%m-%d")

def get_overseas_region(self, instance) -> typing.List[str]:
if instance.country:
Expand Down
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
Loading