Version 2 (modified by Stavros Korokithakis, 12 years ago) (diff)

Fixed debug bug

Page Stats Middleware

Display 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.

The Python Code

import re
from operator import add
from time import time
from django.db import connection

class StatsMiddleware(object):

    def process_view(self, request, view_func, view_args, view_kwargs):

        # turn on debugging in db backend to capture time
        from django.conf import settings
        debug = settings.DEBUG
        settings.DEBUG = True

        # get number of db queries before we do anything
        n = len(connection.queries)

        # set this back so exceptions are properly handled
        debug = settings.DEBUG

        # time the view
        start = time()
        response = view_func(request, *view_args, **view_kwargs)
        totTime = time() - start

        # and once more, to get queries
        settings.DEBUG = True

        # 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:]])
            dbTime = 0.0

        # and backout python time
        pyTime = totTime - dbTime

        # restore debugging setting again
        settings.DEBUG = debug

        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 =
            if match:
                s = s[:match.start('cmt')] + \
          'fmt') % stats + \
                response.content = s

        return response


Put a comment in your template in this format:

<!-- STATS: format_string -->


<!-- STATS: Total: %(totTime).2f Python: %(pyTime).2f DB: %(dbTime).2f Queries: %(queries)d -->
Back to Top