Skip to content

Commit

Permalink
Cache response, return success on repeat request
Browse files Browse the repository at this point in the history
  • Loading branch information
koutst committed Apr 30, 2024
1 parent ceb7dbe commit 8ccf11c
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 10 deletions.
5 changes: 3 additions & 2 deletions src/purchase/tests/test_send_rsc.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,10 +247,11 @@ def test_repeat_request_support_comment_distribution(self):
self.assertContains(response, "id", status_code=201)

# make a second request with the same client_id which should fail.
response = self._post_support_response(
response_repeat_call = self._post_support_response(
user, comment.id, client_id, "rhcommentmodel", tip_amount
)
self.assertEqual(response.status_code, 400)
self.assertEqual(response.data, response_repeat_call.data)
self.assertEqual(response_repeat_call.status_code, 201)

def _post_support_response(
self, user, object_id, client_id, content_type, amount=10
Expand Down
14 changes: 6 additions & 8 deletions src/purchase/views/purchase_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,17 +78,13 @@ def create(self, request):
with transaction.atomic():
user = User.objects.select_for_update().get(id=user.id)

cached_client_id = cache.get(f"purchase_client_id_{client_id}")
if cached_client_id:
cached_serialized_data = cache.get(f"purchase_client_id_{client_id}")
if cached_serialized_data:
return Response(
{
"detail": "This purchase has already been processed",
},
status=400,
cached_serialized_data,
status=201,
)

cache.set(f"purchase_client_id_{client_id}", True, timeout=60)

purchase_data = {
"amount": amount,
"user": user.id,
Expand Down Expand Up @@ -219,6 +215,8 @@ def create(self, request):
serializer = self.serializer_class(purchase, context=context)
serializer_data = serializer.data

cache.set(f"purchase_client_id_{client_id}", serializer_data, timeout=3600)

if recipient and user:
self.send_purchase_notification(
purchase, unified_doc, recipient, notification_type
Expand Down

0 comments on commit 8ccf11c

Please sign in to comment.