【发布时间】:2015-05-04 17:33:47
【问题描述】:
我正在分析我的“即将部署”站点,我已经找到并更正了中间件。原始版本的时间要小得多。
from django.db import connection
from time import time
from operator import add
import re
# http://stackoverflow.com/a/17777539/409102
class StatsMiddleware(object):
def __init__(self):
self.regexp = re.compile(
r'(?P<cmt><!--\s*STATS:(?P<fmt>.*?)ENDSTATS\s*-->)'
)
def process_request(self, request):
request.stats_middleware = ( len(connection.queries), time() )
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 -->
<!-- Q_STATS -->
</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
# time the view
n, start = request.stats_middleware
response = view_func(request, *view_args, **view_kwargs)
# 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
match = self.regexp.search(s)
# compute the db time for the queries just run
db_queries = len(connection.queries) - n
db_time = 0.0
for q in connection.queries[n:]:
db_time += float(q['time'])
if( "prof_sql" in request.GET ):
qq = "<table><thead><tr><td>time</td><td>SQL</td></tr></thead><tbody>"
for q in connection.queries[n:]:
qq += "<tr><td>{0}</td><td>{1}</td></tr>".format(q['time'],q['sql'])
qq += "</tbody></table>"
s = s.replace("<!-- Q_STATS -->", "<br/> Queries<br/>" + qq )
response.content = s
# compute time now
total_time = time() - start
python_time = total_time - db_time
stats = {
'total_time': total_time * 1000,
'python_time': python_time * 1000,
'db_time': db_time * 1000.0,
'db_queries': db_queries,
}
if match:
s = (s[:match.start('cmt')] +
match.group('fmt') % stats +
s[match.end('cmt'):])
response.content = s
return response
这 50 毫秒的差异是最好的情况,“幸运”发生在我要截屏时。
编辑:如果不清楚我在问什么。我不知道我的中间件是不是错了,因为它打印<10ms和chrome打印>60ms,而且我已经做对了。
EDIT2:还是问题太简单了?如果我的中间件没问题,为什么它会打印出不好的结果,以及我该如何“修复它”,以便它将正确的值打印到 HTML。
【问题讨论】:
-
你有什么问题?
-
我的中间件是否有问题,因为中间件打印的内容和 chrome 显示的内容之间存在很大差异......为什么要接近投票? O.o