How to calculate response time in Django Python

后端 未结 4 1259
半阙折子戏
半阙折子戏 2021-01-23 05:19

I am new to Django Python. Please advise how to calculate a response time from the moment where the user input the search criteria until the relevant information are loaded/disp

4条回答
  •  情书的邮戳
    2021-01-23 06:02

    Django is a python framework for backend operations. It's purpose is to process http requests, hence your question "from the moment where the user input the search criteria until the relevant information are loaded/displayed" is very vague in this context. Your question suggests you are looking at some interactive Javascript/Ajax based frontend?

    If you are curious about render times for individual http requests, you may approach this with a custom middleware, something along these lines:

    class StatsMiddleware(object):
        def process_request(self, request):
            "Start time at request coming in"
            request.start_time = time.time()
    
        def process_response(self, request, response):
            "End of request, take time"
            total = time.time() - request.start_time
    
            # Add the header.
            response["X-total-time"] = int(total * 1000)
            return response
    

    Then, add this middleware in the corresponding Django settings.py section:

    MIDDLEWARE_CLASSES = (
      ...
      'app.stats.StatsMiddleware',
      ...
    )
    

    The time it took to produce the response will be added to a custom http header "X-total-time". Note this will involve all rendering, calculation, 3rd party system and DB ops.

提交回复
热议问题