Show number of queries in runserver output

Sometimes I'd like to know how many database queries were used to generate a particular view, but can't be bothered with the full weight of the (otherwise excellent) django-debug-toolbar.

The toolbar does a lot of logging and slows down rendering. Also, by default I want 'INTERCEPT_REDIRECTS': False, but then I don't see the queries used in the form processing (only what was used to render the page redirected to).

So instead I wrote a small piece of middleware that just outputs the query count as part of the runserver console output:

    # queries: 4   [03/Mar/2012 10:20:37] "GET /admin/ HTTP/1.0" 200 23831
    # queries: 114 [03/Mar/2012 10:20:51] "GET /oops/ HTTP/1.0" 200 57321
    # queries: 14  [03/Mar/2012 10:21:07] "GET /admin/members/ HTTP/1.0" 200 37601

Code:

import sys
from django.conf import settings
from django.db import connection
from django.utils import termcolors

class QueryPrintingMiddleware(object):
    start = None

    def process_request(self, request):
        if settings.DEBUG:
            self.start = len(connection.queries)

    def process_response(self, request, response):
        if settings.DEBUG and 'runserver' in sys.argv and self.start is not None:
            red = termcolors.make_style(opts=('bold',), fg='red')
            yellow = termcolors.make_style(opts=('bold',), fg='yellow')

            count = len(connection.queries) - self.start
            output = '# queries: %s' % count
            output = output.ljust(15)

            # add some colour
            if count > 100:
                output = red(output)
            elif count > 10:
                output = yellow(output)

            # runserver just prints its output to sys.stderr, so follow suite
            sys.stderr.write(output)

        return response

Comments !