Django:显示在每个页面上加载页面所需的时间 [英] Django: display time it took to load a page on every page

查看:116
本文介绍了Django:显示在每个页面上加载页面所需的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Django, how can I return the time it took to load a page (not the date) in every page of the site, without having to write in every views.py a code similar to the following one?

start = time.time()
#model operations
loadingpagetime = time.time() - start

如果使用 TEMPLATE_CONTEXT_PROCESSOR 是最好的选择。

我将如何从整个页面加载时间,而不是只得到模板加载时间?

If using a TEMPLATE_CONTEXT_PROCESSOR is the best option.
How would I get the whole page loading time from there, instead of just getting the template loading time?

更新:

由于初始问题不在似乎很清楚,这里是一个方法,将是我想做什么的 Python版本

As the initial question doesn't seem to be clear enough, here is an approach of what would be the Python version of what I want to do.

#!/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>'


推荐答案

您可以创建一个自定义的中间件进行登录。这是我如何创建一个中间件,以实现这一目的基于 http://djangosnippets.org/snippets/358/ (I

You can create a custom middleware to log this. Here is how I create a middleware to achieve this purpose base on http://djangosnippets.org/snippets/358/ (I modified the code a bit).

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

Firstly, assuming your project has a name: test_project, create a file name middlewares.py, I place it in the same folder as 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

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

Secondly, modify settings.py to add your middleware:

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

    # your custom middleware here
    'test_project.middlewares.StatsMiddleware',
)

注意:如上所述,您必须添加到中间件类的完整路径,格式为:

Note: you have to add the full path to your middleware class like above, the format is:

<project_name>.<middleware_file_name>.<middleware_class_name>

第二个注释是我将这个中间件添加到列表的末尾,因为我只想登录模板加载时间单独。如果您要记录模板+所有中间件的加载时间,请将其放在 MIDDLEWARE_CLASSES 列表开始($ @Symmitchry)中。

A second note is I added this middleware to the end of the list because I just want to log the template load time alone. If you want to log the load time of templates + all middlewares, please put it in the beginning of MIDDLEWARE_CLASSES list (credits to @Symmitchry).

返回主题,下一步是修改您的 base.html 或您要加载日志的任何页面,添加以下内容:

Back to the main topic, the next step is to modify your base.html or whatever pages you want to log load time, add this:

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

注意:您可以命名< div id =stats> ; ,并使用CSS,但你想要的,但不要更改评论<! - STATS:.... - > 。如果要更改它,请确保您根据创建的 middlewares.py 中的正则表达式模式进行测试。

Note: you can name the <div id="stats"> and use CSS for that div however you want, but DON'T change the comment <!-- STATS: .... -->. If you want to change it, be sure that you test it against the regex pattern in the created middlewares.py.

Voila,享受统计资料。

Voila, enjoy the statistics.

编辑:

使用CBV(基于类的视图)很多,你可能遇到错误 ContentNotRenderedError 与上面的解决方案。没有恐惧,这里是在 middlewares.py 中的修复:

For those who use CBVs (Class Based Views) a lot, you might have encountered the error ContentNotRenderedError with above solution. Have no fear, here is the fix in 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

我得到它与Django 1.6.x的工作,如果您有其他版本的Django有问题,请在评论部分ping我。

I got it working with Django 1.6.x, if you have problem with other version of Django, please ping me in comment section.

这篇关于Django:显示在每个页面上加载页面所需的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆