Skip to content

Instantly share code, notes, and snippets.

@DanielVF
Created June 17, 2013 13:04
Show Gist options
  • Save DanielVF/5796708 to your computer and use it in GitHub Desktop.
Save DanielVF/5796708 to your computer and use it in GitHub Desktop.
Ghetto Django page profiler
"""
Source, unknown.
Tweaked by Daniel Von Fange.
"""
import sys
import tempfile
import hotshot
import hotshot.stats
from django.conf import settings
from cStringIO import StringIO
from django.db import connection
class ProfileMiddleware(object):
"""
Displays hotshot profiling for any view.
http://yoursite.com/yourview/?prof
Add the "prof" key to query string by appending ?prof (or &prof=)
and you'll see the profiling results in your browser.
It's set up to only be available in django's debug mode,
but you really shouldn't add this middleware to any production configuration.
I add it to my settings.py file on my local dev machine by doing::
from settings_default import MIDDLEWARE_CLASSES
MIDDLEWARE_CLASSES += tuple(['shared.middleware.ProfileMiddleware'])
"""
def process_request(self, request):
if settings.DEBUG and 'prof' in request.GET:
self.tmpfile = tempfile.NamedTemporaryFile()
self.prof = hotshot.Profile(self.tmpfile.name)
def process_view(self, request, callback, callback_args, callback_kwargs):
if settings.DEBUG and 'prof' in request.GET:
return self.prof.runcall(callback, request, *callback_args, **callback_kwargs)
def process_response(self, request, response):
if settings.DEBUG and 'prof' in request.GET:
self.prof.close()
out = StringIO()
old_stdout = sys.stdout
sys.stdout = out
stats = hotshot.stats.load(self.tmpfile.name)
#stats.strip_dirs()
stats.sort_stats('time', 'calls')
stats.print_stats()
sys.stdout = old_stdout
stats_str = out.getvalue()
sql_qs = [""+str(q['time'])+"\t"+q['sql'] for q in connection.queries]
sql_str = "\n".join(sql_qs)
if response and response.content and stats_str:
response.content = "<pre>" + stats_str + "\n\n"+ sql_str+"</pre>"
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment