You can customize a middleware class, then reference the middleware in settings.py, add it to the middleware_classes, and then display the code in the public template.
Code added to the public template:
<div id= "stats" ><!--stats:total:% (tottime). 2FS <br/>python:% (pytime). 2fs<br/>db:% (dbTime). 2FS <br/>queries:% (Queries) d--></div>
Statsmiddleware Middleware Code
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:
{% if debug%} <div id= "stats" ><!--stats:total:% (tottime). 2FS <br/>
Python:% (pytime). 2FS <br/>
DB:% (dbTime). 2FS <br/>
Queries:% (Queries) d--></div> {% endif%}
Here's the CSS style I use:
#stats {font-size:65%; padding:5px;
z-index:1000; Position:absolute; right:5px; top:5px;
-moz-opacity:. 7; Opacity:. 7;}
"""
#This stuff would only happen if debug are already on
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)
Tottime = time ()-Start
# COMPUTE the DB time for the queries just run
queries = Len (connection.queries)-N
If queries:
DbTime = reduce (add, [Float (q[' time '))
For q in Connection.queries[n:]])
Else
DbTime = 0.0
# and Backout python time
Pytime = Tottime-dbtime
Stats = {
' Tottime ': Tottime,
' Pytime ': Pytime,
' DbTime ': DbTime,
' Queries ': Queries,
}
# Replace the comment if found
If Response and Response.content:
s = response.content
RegExp = Re.compile (R ' (? p<cmt><!--\s*stats: (? P<fmt>.*?) ) ')
Match = Regexp.search (s)
If match:
s = S[:match.start (' CMT ')] + \
Match.group (' FMT ')% stats + \
S[match.end (' CMT '):]
Response.content = S
return response
Save As: statsmiddleware.py,
and add it to Settings.py's middleware_classes.
Article reprint: http://www.sharejs.com/codes/python/8638
Django calculates detailed execution time for each page through middleware