I want to check the runtime of views on my site. This can be done by decorators, but since I have dozens of opinions, I thought about doing it in middleware, keeping the original time in the dictionary with the query as a key (see below), but I'm worried about assumptions that I did (see 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 preview logic after the submission.
- The query instance remains the same preview of the instance and after it.
Are these assumptions safe? Is this middleware a good idea?
Iftah source share