Created
February 3, 2015 23:04
-
-
Save jefftriplett/f40de3bacdabce859c65 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Originaly code was taken from: http://djangosnippets.org/snippets/290/ | |
But I was made some improvements like: | |
- print URL from what queries was | |
- don't show queries from static URLs (MEDIA_URL and STATIC_URL, also for /favicon.ico). | |
- If DEBUG is False tell to django to not use this middleware | |
- Remove guessing of terminal width (This breaks the rendered SQL) | |
""" | |
from clint.textui import colored, columns, indent, puts | |
from django.conf import settings | |
from django.core.exceptions import MiddlewareNotUsed | |
from django.db import connection | |
INDENTATION = 2 | |
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. | |
""" | |
def __init__(self): | |
if not settings.DEBUG: | |
raise MiddlewareNotUsed | |
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 | |
with indent(INDENTATION): | |
puts(colored.magenta('[SQL Queries for] ') + colored.blue(request.path_info)) | |
puts() | |
total_time = 0.0 | |
for query in connection.queries: | |
nice_time = '[{0}]'.format(query['time']) | |
nice_sql = query['sql'].replace('"', '').replace(',', ', ') | |
total_time = total_time + float(query['time']) | |
puts( | |
columns( | |
[colored.red(nice_time), 10], | |
[colored.white(nice_sql), 120], | |
) | |
) | |
puts() | |
puts(colored.green("[TOTAL TIME: %s seconds (%s queries)]" % ( | |
str(total_time), str(len(connection.queries))))) | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment