I want to check the execution time of views in my site. This can be done by decorators, but since I have dozens of views I thought of doing it in a middleware, saving the initial time in a dictionary with the request as a key (see below), but I'm worried about assumptions I made (see farther below):
class SlowWarningMiddleware:
def __init__(self):
self.time_tracking = {}
def process_view(self, request, view_func, view_args, view_kwargs):
self.time_tracking[request] = time.time()
def process_response(self, request, response):
if request not in self.time_tracking:
return response
delta = time.time() - self.time_tracking[request]
def process_exception(self, request, exception):
if request not in self.time_tracking:
return
delta = time.time() - self.time_tracking[request]
this code assumes two points:
- The same middleware instance handles the pre-view and post-view logic.
- The request instance remains the same instance pre-view and post-view.
are these assumptions safe? is this middleware a good idea?