Changes between Initial Version and Version 1 of PageStatsMiddleware


Ignore:
Timestamp:
Aug 12, 2006, 10:39:53 PM (18 years ago)
Author:
Gary Wilson <gary.wilson@…>
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • PageStatsMiddleware

    v1 v1  
     1= Page Stats Middleware =
     2
     3Display performance metrics measured during the generation of a page. Allows you to display total time, python time, database time, and number of queries for the rendered page.
     4
     5== The Python Code ==
     6
     7{{{
     8#!python
     9import re
     10from operator import add
     11from time import time
     12from django.db import connection
     13
     14class StatsMiddleware(object):
     15
     16    def process_view(self, request, view_func, view_args, view_kwargs):
     17
     18        # turn on debugging in db backend to capture time
     19        from django.conf import settings
     20        debug = settings.DEBUG
     21        settings.DEBUG = True
     22
     23        # get number of db queries before we do anything
     24        n = len(connection.queries)
     25
     26        # time the view
     27        start = time()
     28        response = view_func(request, *view_args, **view_kwargs)
     29        totTime = time() - start
     30
     31        # compute the db time for the queries just run
     32        queries = len(connection.queries) - n
     33        if queries:
     34            dbTime = reduce(add, [float(q['time'])
     35                                  for q in connection.queries[n:]])
     36        else:
     37            dbTime = 0.0
     38
     39        # and backout python time
     40        pyTime = totTime - dbTime
     41
     42        # restore debugging setting
     43        settings.DEBUG = debug
     44
     45        stats = {
     46            'totTime': totTime,
     47            'pyTime': pyTime,
     48            'dbTime': dbTime,
     49            'queries': queries,
     50            }
     51
     52        # replace the comment if found           
     53        if response and response.content:
     54            s = response.content
     55            regexp = re.compile(r'(?P<cmt><!--\s*STATS:(?P<fmt>.*?)-->)')
     56            match = regexp.search(s)
     57            if match:
     58                s = s[:match.start('cmt')] + \
     59                    match.group('fmt') % stats + \
     60                    s[match.end('cmt'):]
     61                response.content = s
     62
     63        return response
     64}}}
     65
     66
     67== The HTML ==
     68
     69Put a comment in your template in this format:
     70{{{
     71<!-- STATS: format_string -->
     72}}}
     73
     74Example:
     75{{{
     76<!-- STATS: Total: %(totTime).2f Python: %(pyTime).2f DB: %(dbTime).2f Queries: %(queries)d -->
     77}}}
Back to Top