Py学习  »  Django

django-测量中间件中的延迟

Max • 5 年前 • 1467 次点击  

我为django 1.8编写了这段代码,以计算处理请求所需的时间。我故意让视图花费4秒,但此代码中显示的增量时间是8毫秒。 有什么办法可以在中间件中测量它吗?

from datetime import datetime

class MonitorMiddleware(object):
    def process_request(self, request):
        request.start = datetime.now()

    def process_response(self, request, response):
        print 'Took: ', round((datetime.now() - request.start).microseconds / 1000000.0, 3)
        return response
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/49859
 
1467 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Emmanuel Mtali
Reply   •   1 楼
Emmanuel Mtali    6 年前

我不确定你的时间计算是否正确。我已经深入研究了 django-request-profiler 并编译了一个简短的实现方法。

from django.utils import timezone
class ProfilingMiddleware:
    def process_request(self, request):
        self.start_ts = timezone.now()

    def process_response(self, request, response):
        self.end_ts = timezone.now()
        duration = (self.end_ts - self.start_ts).total_seconds()
        return response

我强烈建议您使用开源django分析器。