Login

Template tag to dump database query info

Author:
pryankster
Posted:
April 6, 2007
Language:
Python
Version:
.96
Tags:
tag db debugging
Score:
6 (after 6 ratings)

This snippet introduces two tags: {%dbinfo%} and {%dbquerylist%}. The {%dbinfo%} tag returns a string with the # of database queries and aggregate DB time. The {%dbquerylist%} tag expands to a set of <LI> elements containing the actual SQL queries executed. If settings.TEMPLATE_DEBUG is False, both tags return empty strings.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
rom django.template import Node
from django.template import Library
from django.conf import settings
import django.db as db
import re
from django.utils.html import escape

register = Library()

class DbInfoNode(Node):
    def __init__(self):
        pass

    def __repr__(self):
        return "<DbInfoNode>"

    def render(self, context):
        if not settings.TEMPLATE_DEBUG:
            return ""
        secs = 0.0
        for s in db.connection.queries:
            secs += float(s['time']);
        return str("%d queries, %f seconds" % (len(db.connection.queries), secs)
)

def do_dbinfo(parser, token):
    return DbInfoNode()
do_dbinfo = register.tag('dbinfo', do_dbinfo)

class DbQueryListNode(Node):
    def __init__(self):
        pass

    def __repr__(self):
        return "<DbQueryListNode>"

    def render(self, context):
        if not settings.TEMPLATE_DEBUG:
            return ""
        s = ""
        for q in db.connection.queries:
            s += "<li>" + escape(q["sql"]) + "</li>\n"
        return s

def do_dbquerylist(parser, token):
    return DbQueryListNode()

do_dbquerylist = register.tag('dbquerylist', do_dbquerylist)

More like this

  1. A GET string modifier templatetag by cogat 6 years, 5 months ago
  2. Template tags/filter for working with query strings by gonz 7 years, 4 months ago
  3. Generate QR Code image for a string by johnnoone 6 years ago
  4. Template tag which gets specific GET variables from the current request by aruseni.magiku 5 years, 2 months ago
  5. Yet another query string template tag by atms 4 years, 1 month ago

Comments

Please login first before commenting.