How to calculate response time in Django Python

后端 未结 4 1105
半阙折子戏
半阙折子戏 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:09

    Here’s the class that does the entire thing

    import time
    
    
    class StatsMiddleware(object):
    
        def process_request(self, request):
            "Store the start time when the request comes in."
            request.start_time = time.time()
    
        def process_response(self, request, response):
            "Calculate and output the page generation duration"
            # Get the start time from the request and calculate how long
            # the response took.
            duration = time.time() - request.start_time
    
            # Add the header.
            response["X-Page-Generation-Duration-ms"] = int(duration * 1000)
            return response
    

    That’s all there’s to it. Just store the time when the request comes in, and retrieve it later.

    To install the middleware above, just add it to your settings.py:

    MIDDLEWARE_CLASSES = (
        'project.stats_middleware.StatsMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        ...
    )
    

提交回复
热议问题