Skip to content

Instantly share code, notes, and snippets.

@girasquid
Created December 23, 2009 21:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save girasquid/262837 to your computer and use it in GitHub Desktop.
Save girasquid/262837 to your computer and use it in GitHub Desktop.
Basic, quick profiling middleware.
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