implemented response timing via time_view
decorator
This commit is contained in:
26
utils/decorators.py
Normal file
26
utils/decorators.py
Normal file
@@ -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
|
Reference in New Issue
Block a user