我试图检索每个视图的一些加载时间,并将其显示在页面中。为此,我使用了middleware
和context_processor
设置,但找不到将这些值检索到视图上下文的方法。你知道吗
以下是示例:
我已经将middleware
和context_processor
添加到设置中。
你知道吗中间件.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
上下文_处理器.py你知道吗
#from django.template import RequestContext
def foo(request):
context_data = dict()
context_data["stats"] = "stats"
return context_data
你知道吗视图.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})
你知道吗索引.html地址:
{{stats}}
<br>
{% for user in users_list %}
{{user}} <br>
{% endfor %}
检索这些值的正确方法是什么?其思想是稍后将这些值与缓存框架进行比较。你知道吗
目前没有回答
相关问题 更多 >
编程相关推荐