Skip to content

Instantly share code, notes, and snippets.

@dokkaebi
Created September 9, 2015 18:38
Show Gist options
  • Save dokkaebi/9252bd24b8772b56ed19 to your computer and use it in GitHub Desktop.
Save dokkaebi/9252bd24b8772b56ed19 to your computer and use it in GitHub Desktop.
Django middleware to print nicely colored list of sql queries at the end of each request
class SQLPrintingMiddleware(object):
"""
Middleware which prints out a list of all SQL queries done
for each view that is processed. This is only useful for debugging.
https://gist.github.com/vstoykov/1390853
Modified locally to depend on settings.DEBUG_SQL, as I don't think this is something we generally want on a dev box.
Also added some more coloring, and a line to hide the (usually long) list of fields in the select clause.
"""
def __init__(self):
if not settings.DEBUG or not getattr(settings, 'DEBUG_SQL', False):
raise MiddlewareNotUsed
try:
import colors
except ImportError:
self.has_colors = False
else:
self.has_colors = True
def process_response(self, request, response):
if (len(connection.queries) == 0 or
request.path_info.startswith('/favicon.ico') or
request.path_info.startswith(settings.STATIC_URL) or
request.path_info.startswith(settings.MEDIA_URL)):
return response
indentation = 2
print "\n\n%s\033[1;35m[SQL Queries for]\033[1;34m %s\033[0m\n" % (" " * indentation, request.path_info)
total_time = 0.0
for query in connection.queries:
nice_sql = query['sql'].replace('"', '')
# Hide the gory details
nice_sql = re.sub(r'SELECT .* FROM', 'SELECT (...) FROM', nice_sql)
if self.has_colors:
from colors import cyan, green, yellow
# colored words in the middle of the subquery break this
# nice_sql = re.sub(r'\((.+)\)', yellow('(\\1)'), nice_sql)
nice_sql = re.sub(r'FROM `([^`]+)`', 'FROM %s' % yellow('`\\1`'), nice_sql)
nice_sql = nice_sql\
.replace('(', green('('))\
.replace(')', green(')'))\
.replace('SELECT', cyan('SELECT'))\
.replace('COUNT', cyan('COUNT'))\
.replace('LIMIT', cyan('LIMIT'))\
.replace('FROM', cyan('FROM'))\
.replace('WHERE', cyan('WHERE'))\
.replace('JOIN', cyan('JOIN'))\
.replace('ON', cyan('ON'))\
.replace('AND', cyan('AND'))
sql = "\033[1;31m[%s]\033[0m %s" % (query['time'], nice_sql)
total_time = total_time + float(query['time'])
print "%s%s\n" % (" " * indentation, sql)
replace_tuple = (" " * indentation, str(total_time), str(len(connection.queries)))
print "%s\033[1;32m[TOTAL TIME: %s seconds (%s queries)]\033[0m" % replace_tuple
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment