我正在尝试检索每个视图的一些加载时间并在页面中显示它。为此,我使用的是middleware
和context_processor
设置,但我无法找到将此值检索到视图上下文的方法。
以下是示例:
我已将middleware
和context_processor
添加到设置中。
middlewares.py(来自this回答):
from __future__ import unicode_literals, absolute_import
from django.db import connection
from time import time
from operator import add
import re
from functools import reduce
class StatsMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
# 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,
}
# this works fine
print(stats)
# 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
# The following code is commented
# because it can't compile bytes and
# as long as I understand the values comes
# from the rendered template which are the ones I'm interested in getting
# 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
context_processors.py
#from django.template import RequestContext
def foo(request):
context_data = dict()
context_data["stats"] = "stats"
return context_data
views.py:
from django.shortcuts import render
from accounts.models import User
def myFunc(request):
users = User.objects.all()
return render(request, 'index.html, {'users_list': users})
的index.html:
{{stats}}
<br>
{% for user in users_list %}
{{user}} <br>
{% endfor %}
检索这些值的正确方法是什么?我们的想法是稍后将这些值与缓存框架进行比较。