您可以创建自定义middleware来记录此情况.下面是我如何基于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
其次,修改settings.py
以添加您的中间件:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
# ... your existing middlewares ...
# your custom middleware here
'test_project.middlewares.StatsMiddleware',
)
注意:您必须像上面那样向中间件类添加完整路径,格式如下:
<project_name>.<middleware_file_name>.<middleware_class_name>
第二个注意事项是,我将这个中间件添加到列表的末尾,因为我只想单独记录模板加载时间.如果您想记录模板+所有中间件的加载时间,请将其放在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>
注意:您可以随心所欲地命名<div id="stats">
并对该div使用CSS,但不要更改注释<!-- STATS: .... -->
.如果您想要更改它,请确保根据创建的middlewares.py
中的正则表达式模式对其进行测试.
瞧,好好享受统计数据吧.
EDIT:个
对于那些经常使用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
我用Django 1.6实现了.x、 如果你对Django的其他版本有问题,请在 comments 区给我打电话.