Django:显示在每个页面上加载页面所花费的时间

zur*_*fyx 35 python django

在Django中,如何在网站的每个页面中返回加载页面(而不是日期)所花费的时间,不必在每个views.py中写入类似于以下代码的代码?

start = time.time()
#model operations
loadingpagetime = time.time() - start
Run Code Online (Sandbox Code Playgroud)

如果使用a TEMPLATE_CONTEXT_PROCESSOR是最佳选择.
如何从那里获得整个页面加载时间,而不是仅仅获取模板加载时间?

更新:

由于最初的问题似乎不够明确,这里有一个方法,我想做的Python版本.

#!/usr/bin/env python
import cgitb; cgitb.enable() 
import time
print 'Content-type: text/html\n\n'

start = time.time()

print '<html>'
print '<head>'
print '</head>'
print '<body>'
print '<div>HEADER</div>'
print '<div>'
print '<p>Welcome to my Django Webpage!</p>'
print '<p>Welcome to my Django Webpage!</p>'
print '<p>Welcome to my Django Webpage!</p>'
print '</div>'

time.sleep(3)
loadingtime = time.time() - start

print '<div>It took ',loadingtime,' seconds to load the page</div>'
print '</body>'
print '</html>'
Run Code Online (Sandbox Code Playgroud)

Hie*_*yen 64

您可以创建自定义中间件来记录它.以下是我如何基于http://djangosnippets.org/snippets/358/创建一个实现此目的的中间件(我稍微修改了一下代码).

首先,假设您的项目有一个名称:test_project,创建一个文件名middlewares.py,我将它放在同一个文件夹中settings.py:

from django.db import connection
from time import time
from operator import add
import re


class StatsMiddleware(object):

    def process_view(self, request, view_func, view_args, view_kwargs):
        '''
        In your base template, put this:
        <div id="stats">
        <!-- STATS: Total: %(total_time).2fs Python: %(python_time).2fs DB: %(db_time).2fs Queries: %(db_queries)d ENDSTATS -->
        </div>
        '''

        # Uncomment the following if you want to get stats on DEBUG=True only
        #if not settings.DEBUG:
        #    return None

        # get number of db queries before we do anything
        n = len(connection.queries)

        # time the view
        start = time()
        response = view_func(request, *view_args, **view_kwargs)
        total_time = time() - start

        # compute the db time for the queries just run
        db_queries = len(connection.queries) - n
        if db_queries:
            db_time = reduce(add, [float(q['time'])
                                   for q in connection.queries[n:]])
        else:
            db_time = 0.0

        # and backout python time
        python_time = total_time - db_time

        stats = {
            'total_time': total_time,
            'python_time': python_time,
            'db_time': db_time,
            'db_queries': db_queries,
        }

        # replace the comment if found
        if response and response.content:
            s = response.content
            regexp = re.compile(r'(?P<cmt><!--\s*STATS:(?P<fmt>.*?)ENDSTATS\s*-->)')
            match = regexp.search(s)
            if match:
                s = (s[:match.start('cmt')] +
                     match.group('fmt') % stats +
                     s[match.end('cmt'):])
                response.content = s

        return response
Run Code Online (Sandbox Code Playgroud)

其次,修改settings.py以添加您的中间件:

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    # ... your existing middlewares ...

    # your custom middleware here
    'test_project.middlewares.StatsMiddleware',
)
Run Code Online (Sandbox Code Playgroud)

注意:您必须像上面一样添加中间件类的完整路径,格式为:

<project_name>.<middleware_file_name>.<middleware_class_name>
Run Code Online (Sandbox Code Playgroud)

第二个注意事项是我将此中间件添加到列表的末尾,因为我只想记录模板加载时间.如果要记录模板+所有中间件的加载时间,请将其放在MIDDLEWARE_CLASSES列表的开头(@Symmitchry的信用).

回到主题,下一步是修改您base.html想要记录加载时间的页面,添加:

<div id="stats">
<!-- STATS: Total: %(total_time).2fs Python: %(python_time).2fs DB: %(db_time).2fs Queries: %(db_queries)d ENDSTATS -->
</div>
Run Code Online (Sandbox Code Playgroud)

注意:您可以根据<div id="stats">需要为该div 命名并使用CSS,但不要更改注释<!-- STATS: .... -->.如果要更改它,请确保根据创建的正则表达式模式对其进行测试middlewares.py.

瞧,享受统计数据.

编辑:

对于那些经常使用CBV(基于类的视图)的人,您可能会遇到ContentNotRenderedError上述解决方案的错误.不用担心,这里有修复middlewares.py:

    # replace the comment if found
    if response:
        try:
            # detects TemplateResponse which are not yet rendered
            if response.is_rendered:
                rendered_content = response.content
            else:
                rendered_content = response.rendered_content
        except AttributeError:  # django < 1.5
            rendered_content = response.content
        if rendered_content:
            s = rendered_content
            regexp = re.compile(
                r'(?P<cmt><!--\s*STATS:(?P<fmt>.*?)ENDSTATS\s*-->)'
            )
            match = regexp.search(s)
            if match:
                s = (s[:match.start('cmt')] +
                     match.group('fmt') % stats +
                     s[match.end('cmt'):])
                response.content = s

    return response
Run Code Online (Sandbox Code Playgroud)

我使用Django 1.6.x,如果你有其他版本的Django有问题,请在评论部分ping我.

  • 注意!此实现只是跳过所有以下中间件的process_view方法.这可能不是预期的...... (3认同)

mes*_*shy 20

Geordi为您提供了请求周期中发生的所有事情的精彩细分.它是一个中间件,可以生成一个完整的调用树,以准确显示正在发生的事情以及每个函数花费的时间.

它看起来像这样:

在此输入图像描述

我强烈推荐它 :)

图片来源:http://evzijst.bitbucket.org/pycon.in