Measuring view runtime in Django middleware - good idea?

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?

+6
source share
2 answers

Reading Is Django Middleware Safe? gave me a better idea:
To add an attribute to the request object (i.e. request.start_time = time.time() before executing the view).

This avoids assumption 1 and removes the dangerous potential for collecting β€œzombie” elements in a dictionary that will never be cleared.

This also slightly reduces Assumption 2, because if at some point a new copy of the request is created, it will still work if the attributes are copied (as is done in the python copy module).

And even as a bonus it has less code, fewer errors and readability :)

+5
source

Use this simple view to calculate runtime, it also works for views that need user input, it displays runtime on a simple page

  def test(request): from django.test.client import Client import time c = Client() #client login if needed response = c.post('/login/', {'username': 'admin', 'password': 'password'}) start = time.time() response = c.get('/pagetotest/') #print response #print 'Finished, time: ', time.time() - start # output to console end=time.time() - start return render(request,'loadingtime.html',{'time':end}) 

For you case, using a loop for all of your pages hope this helps someone

+1
source

Source: https://habr.com/ru/post/890856/


All Articles