Profiling middleware using cProfile

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import sys
import cProfile
from cStringIO import StringIO
from django.conf import settings

class ProfilerMiddleware(object):
    def process_view(self, request, callback, callback_args, callback_kwargs):
        if settings.DEBUG and 'prof' 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 and 'prof' 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()
        return response

More like this

  1. Profiling Middleware w/sorting by petrilli 4 years, 10 months ago
  2. Extended Profiling and Timing Middleware using cProfile by dstryke 5 months, 3 weeks ago
  3. Profiling Middlware by udfalkso 7 years ago
  4. Extended Profiling Middleware by hauser 6 years, 2 months ago
  5. Interactive Profiling Middleware by sfllaw 3 years, 8 months ago

Comments

mbi (on April 28, 2008):

It's lacking an 'import sys' somewhere, but works fine otherwise.

#

tuanopenid (on September 11, 2010):

Thank you!

#

(Forgotten your password?)