From cc88de2c69c4bdcb899de8648d63ffa1ad13d022 Mon Sep 17 00:00:00 2001 From: tyrin Date: Thu, 2 Oct 2025 13:32:09 +0300 Subject: [PATCH] implemented response timing via `time_view` decorator --- utils/__init__.py | 0 utils/decorators.py | 26 ++++++++++++++++++++++++++ views.py | 6 ++++++ 3 files changed, 32 insertions(+) create mode 100644 utils/__init__.py create mode 100644 utils/decorators.py diff --git a/utils/__init__.py b/utils/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/utils/decorators.py b/utils/decorators.py new file mode 100644 index 0000000..cb69574 --- /dev/null +++ b/utils/decorators.py @@ -0,0 +1,26 @@ +import time +from functools import wraps +from rest_framework.response import Response + + +def time_view(view_func): + """Decorator to measure the execution time and add it to the JSON response.""" + + @wraps(view_func) + def wrapper(request, *args, **kwargs): + + start_time = time.perf_counter() + + response = view_func(request, *args, **kwargs) + + end_time = time.perf_counter() + elapsed_time = end_time - start_time + + if isinstance(response, Response) and isinstance(response.data, dict): + response.data["time_elapsed_seconds"] = f"{elapsed_time:.4f}" + + print(f"[{view_func.__name__}] Time elapsed: {elapsed_time:.4f} seconds") + + return response + + return wrapper diff --git a/views.py b/views.py index 278f92b..43d77ef 100644 --- a/views.py +++ b/views.py @@ -31,6 +31,9 @@ from rest_framework.response import Response from rest_framework import status from uplim.models import Pixel, CatalogSource +from .utils.decorators import time_view +from django.utils.decorators import method_decorator + # SANITIZE RESPONSE DATA BEFORE JSON CONVERSION FOR DEBUGGING NANS # now NaNs are converted to 'null' beforehand # **************************************************************** @@ -70,6 +73,7 @@ def parse_survey_param(raw): # ************************************************************** +@method_decorator(time_view, name="dispatch") class PixelAggregateView(APIView): def get(self, request): @@ -132,6 +136,7 @@ class PixelAggregateView(APIView): # ************************************************************** +@method_decorator(time_view, name="dispatch") class UpperLimitView(APIView): """ Calculate confidence bounds based on aperture photometry using classic and bayesian methods @@ -538,6 +543,7 @@ class UpperLimitView(APIView): return Response(clean, status=status.HTTP_200_OK) +@method_decorator(time_view, name="dispatch") class StackedUpperLimitView(APIView): """ Calculate confidence bounds based on aperture photometry using classic and bayesian methods for a set of sources