Profiling Middlware

 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
import sys
import tempfile
import hotshot
import hotshot.stats
from django.conf import settings
from cStringIO import StringIO

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.
    * Only tested on Linux
    """
    def process_request(self, request):
        if settings.DEBUG and request.GET.has_key('prof'):
            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 request.GET.has_key('prof'):
            return self.prof.runcall(callback, request, *callback_args, **callback_kwargs)

    def process_response(self, request, response):
        if settings.DEBUG and request.GET.has_key('prof'):
            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()

            if response and response.content and stats_str:
                response.content = "<pre>" + stats_str + "</pre>"

        return response

More like this

  1. Extended Profiling Middleware by hauser 6 years, 2 months ago
  2. Profiling middleware using cProfile by sgb 5 years, 11 months ago
  3. pycallgraph by roppert 5 years, 2 months ago
  4. Interactive Profiling Middleware by sfllaw 3 years, 8 months ago
  5. Profiling Middleware w/sorting by petrilli 4 years, 10 months ago

Comments

nikto (on April 25, 2007):

FWIW for me this didn't work on windows. I needed to switch to mkstemp since NamedTemporaryFile doesn't seem to like you re-opening the file on windows. After making that change and adding os.unlink its all good now.

#

udfalkso (on May 2, 2007):

Thanks nikto. I've only tested this on linux.

#

pootow (on June 10, 2007):

Very helpful, thanks!

#

Tobu (on November 23, 2007):

The imports went missing, here they are:

import sys
import tempfile
import hotshot
import hotshot.stats
from django.conf import settings
from cStringIO import StringIO

#

fisher (on February 3, 2008):

Works ok on Mac OS X (Python 2.4.4)

#

Tobu (on August 22, 2008):

With a recent django (1.0b1), you get:

AttributeError: 'WSGIRequest' object has no attribute 'has_key'

This is fixed by replacing request.has_key with request.GET.has_key .

#

bvemu (on October 5, 2009):

Exactly what I was looking for

Thanks a lot !!

#

Cerinin (on September 16, 2011):

This doesn't work for me on Ubuntu. It causes the request to hang indefinitely...

#

Cerinin (on September 19, 2011):

Error 330 (net::ERR_CONTENT_DECODING_FAILED): Unknown error.

#

divkis01 (on September 23, 2011):

I get the following error: Not sure what is causing this. Given hotshot is no more maintained, I see no reference to similar issues found by others. I tried using cProfile but the syntax for cProfile somehow doesn't allow me to work with callbacks passed to the process_view.

profile_middleware.py", line 61, in process_view stats = hotshot.stats.load(filename) File "/usr/lib/python2.6/hotshot/stats.py", line 15, in load return StatsLoader(filename).load() File "/usr/lib/python2.6/hotshot/stats.py", line 54, in load assert not self._stack AssertionError

#

(Forgotten your password?)