How to calculate response time in Django Python

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

    Since Django 1.10 this works differently now.

    https://docs.djangoproject.com/en/3.0/topics/http/middleware/

    The new style would be as follows:

    import time
    
    
    class StatsMiddleware:
        def __init__(self, get_response):
            self.get_response = get_response
    
        def __call__(self, request):
            start_time = time.time()
    
            response = self.get_response(request)
    
            duration = time.time() - start_time
    
            # Add the header. Or do other things, my use case is to send a monitoring metric
            response["X-Page-Generation-Duration-ms"] = int(duration * 1000)
            return response
    

    No need to store the start time on the request object and retrieve because it all happens in the same method.

    It can also be done in a simple function style instead of a class:

    import time
    
    
    def stats_middleware(get_response):
    
        def middleware(request):
            start_time = time.time()
    
            response = get_response(request)
    
            duration = time.time() - start_time
    
            response["X-Page-Generation-Duration-ms"] = int(duration * 1000)
            return response
    
        return middleware
    

提交回复
热议问题