Just put it in your python path and add it into MIDDLEWARE_CLASSES.
I know that there are a couple of snippets on this site that do something similar to this, but none of them quite suited me.
I wanted something that would indent and space the SQL so that I could differentiate it from the other output from the development server.
Also, I wanted something that would output total query execution time, which my solution does. I just hope that it's useful for someone else, too!
UPDATE: Now this should no longer get upset when running it on windows.
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 | from django.db import connection
from django.conf import settings
import os
def terminal_width():
"""
Function to compute the terminal width.
WARNING: This is not my code, but I've been using it forever and
I don't remember where it came from.
"""
width = 0
try:
import struct, fcntl, termios
s = struct.pack('HHHH', 0, 0, 0, 0)
x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
width = struct.unpack('HHHH', x)[1]
except:
pass
if width <= 0:
try:
width = int(os.environ['COLUMNS'])
except:
pass
if width <= 0:
width = 80
return width
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 process_response(self, request, response):
indentation = 2
if len(connection.queries) > 0 and settings.DEBUG:
width = terminal_width()
total_time = 0.0
for query in connection.queries:
nice_sql = query['sql'].replace('"', '').replace(',',', ')
sql = "\033[1;31m[%s]\033[0m %s" % (query['time'], nice_sql)
total_time = total_time + float(query['time'])
while len(sql) > width-indentation:
print "%s%s" % (" "*indentation, sql[:width-indentation])
sql = sql[width-indentation:]
print "%s%s\n" % (" "*indentation, sql)
replace_tuple = (" "*indentation, str(total_time))
print "%s\033[1;32m[TOTAL TIME: %s seconds]\033[0m" % replace_tuple
return response
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 4 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Very nice, I'm using it in my development environment.
#
This is great, thank you!
#
Exactly what I was looking for, thank you.
#
What is the exact line that goes into MIDDLEWARE_CLASSES?
#
Please login first before commenting.