Last active

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Django cProfile middleware

View profile_middleware.py
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.core.exceptions import MiddlewareNotUsed
from django.conf import settings
import cProfile
import pstats
import marshal
from cStringIO import StringIO
 
class ProfileMiddleware(object):
def __init__(self):
if not settings.DEBUG:
raise MiddlewareNotUsed()
self.profiler = None
 
def process_view(self, request, callback, callback_args, callback_kwargs):
if settings.DEBUG and ('profile' in request.GET
or 'profilebin' 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 settings.DEBUG:
if 'profile' in request.GET:
self.profiler.create_stats()
out = StringIO()
stats = pstats.Stats(self.profiler, stream=out)
# Values for stats.sort_stats():
# - calls call count
# - cumulative cumulative time
# - file file name
# - module file name
# - pcalls primitive call count
# - line line number
# - name function name
# - nfl name/file/line
# - stdname standard name
# - time internal time
stats.sort_stats('time').print_stats(.2)
response.content = out.getvalue()
response['Content-type'] = 'text/plain'
if 'profilebin' in request.GET:
self.profiler.create_stats()
response.content = marshal.dumps(self.profiler.stats)
filename = request.path.strip('/').replace('/','_') + '.pstat'
response['Content-Disposition'] = \
'attachment; filename=%s' % (filename,)
response['Content-type'] = 'application/octet-stream'
return response
haron commented

Thank you! That's really useful.

Nice things. I've mod a little modification to make it working on redirects by adding third "if":

if ('profile' in request.GET or 'profilebin' in request.GET) and 'Location' in response:
    del response['Location']

And you actually need one "return response" at the and of method, not in each "if" block.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.