Created
December 23, 2009 21:45
-
-
Save girasquid/262837 to your computer and use it in GitHub Desktop.
Basic, quick profiling middleware.
This file contains 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
from django.http import HttpResponse | |
from cStringIO import StringIO | |
import cProfile, pstats, sys | |
from django.db import connection | |
class ProfileMiddleware(): | |
def process_view(self, request, callback, callback_args, callback_kwargs): | |
if 'profile' in request.GET: | |
self.profiler = cProfile.Profile() | |
args = (request,) + callback_args | |
return self.profiler.runcall(callback, *args, **callback_kwargs) | |
def process_response(self, request, response): | |
if 'profile' in request.GET: | |
self.profiler.create_stats() | |
out = StringIO() | |
old_stdout, sys.stdout = sys.stdout, out | |
self.profiler.print_stats(1) | |
sys.stdout = old_stdout | |
response.content = '<pre>%s</pre>' % out.getvalue() | |
if 'sql' in request.GET: | |
queries = connection.queries | |
total_time = 0.0 | |
for query in queries: | |
total_time += float(query['time']) | |
query['sql'] = query['sql'].replace('`,`', '`, `') | |
query['sql'] = query['sql'].replace('` FROM `', '` \n FROM `') | |
query['sql'] = query['sql'].replace('` WHERE ', '` \n WHERE ') | |
query['sql'] = query['sql'].replace(' ORDER BY ', ' \n ORDER BY ') | |
from operator import itemgetter | |
queries = sorted(queries, key=itemgetter('time')) | |
queries.reverse() | |
# TODO: pretty up the SQL(see debug panel) | |
output = "Total SQL Time: %s seconds (%s queries)." % (total_time, len(queries)) | |
output = "%s<table><tr><td><strong>Time</strong></td><td><strong>SQL</strong></td></tr>" % output | |
for query in queries: | |
output = "%s<tr><td>%s</td><td><pre>%s</pre></td></tr>" % (output, query['time'], query['sql']) | |
response.content = output | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment