From a980c15974e4a809c5ab94284db12896dffc09f0 Mon Sep 17 00:00:00 2001 From: Reckless_Satoshi <90936742+Reckless-Satoshi@users.noreply.github.com> Date: Sun, 23 Jul 2023 19:27:37 +0000 Subject: [PATCH] Add object limit to /api/ticks (#747) --- api/oas_schemas.py | 25 +++++++++++++++++++++++++ api/views.py | 30 +++++++++++++++++++++++++++--- 2 files changed, 52 insertions(+), 3 deletions(-) diff --git a/api/oas_schemas.py b/api/oas_schemas.py index 511df84e..4b8a425c 100644 --- a/api/oas_schemas.py +++ b/api/oas_schemas.py @@ -869,6 +869,31 @@ class TickViewSchema: "description": "Get all market ticks. Returns a list of all the market ticks since inception.\n" "CEX price is also recorded for useful insight on the historical premium of Non-KYC BTC. " "Price is set when taker bond is locked.", + "parameters": [ + OpenApiParameter( + name="start", + location=OpenApiParameter.QUERY, + description="Start date formatted as DD-MM-YYYY", + required=False, + type=str, + ), + OpenApiParameter( + name="end", + location=OpenApiParameter.QUERY, + description="End date formatted as DD-MM-YYYY", + required=False, + type=str, + ), + ], + "examples": [ + OpenApiExample( + "Too many ticks", + value={ + "bad_request": "More than 5000 market ticks have been found. Try narrowing the date range." + }, + status_codes=[400], + ) + ], } diff --git a/api/views.py b/api/views.py index 67f3affe..b2200e61 100644 --- a/api/views.py +++ b/api/views.py @@ -1091,9 +1091,33 @@ class TickView(ListAPIView): @extend_schema(**TickViewSchema.get) def get(self, request): - data = self.serializer_class( - self.queryset.all(), many=True, read_only=True - ).data + start_date_str = request.query_params.get("start") + end_date_str = request.query_params.get("end") + + # Perform the query with date range filtering + try: + if start_date_str: + start_date = datetime.strptime(start_date_str, "%d-%m-%Y").date() + self.queryset = self.queryset.filter(timestamp__gte=start_date) + if end_date_str: + end_date = datetime.strptime(end_date_str, "%d-%m-%Y").date() + self.queryset = self.queryset.filter(timestamp__lte=end_date) + except ValueError: + return Response( + {"bad_request": "Invalid date format"}, + status=status.HTTP_400_BAD_REQUEST, + ) + + # Check if the number of ticks exceeds the limit + if self.queryset.count() > 5000: + return Response( + { + "bad_request": "More than 5000 market ticks have been found. Please, narrow the date range" + }, + status=status.HTTP_400_BAD_REQUEST, + ) + + data = self.serializer_class(self.queryset, many=True, read_only=True).data return Response(data, status=status.HTTP_200_OK)