Appending the request URL to SQL statements in Django

By Chris Lamb

import sys

from django.http import HttpRequest
from django.db.backends import BaseDatabaseWrapper, util

class URLCursor(util.CursorDebugWrapper):
    def execute(self, sql, *args):
        f = sys._getframe()
        while f:
            request = f.f_locals.get('request')
            if isinstance(request, HttpRequest):
                sql += ' -- %s' % repr(request.path)[2:-1].replace('%', '%%')
                break
            f = f.f_back

        return self.cursor.execute(sql, *args)

fn = BaseDatabaseWrapper.cursor
BaseDatabaseWrapper.cursor = lambda self: URLCursor(fn(self), self)

Now your SQL statements look like:

SELECT "auth_user"."id", [..] WHERE "auth_user"."id" = 1 -- /login

This allows you to quickly go from a misbehaving query in your production environment to the view that is executing it.


Chris Lamb is a freelance Django developer and Debian developer. You can read other posts by me, see software I have written or read more about me. You can also follow me @lolamby.


Tags: Hacks Django

Planets: WUGLUG UWCS Debian ALUG

Tuesday 1st June 2010


Three comments