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.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.has_key('prof'):
            return self.prof.runcall(callback, request, *callback_args, **callback_kwargs)

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

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.

#

msgre (on June 10, 2007):

For those (like me), that haven't experience in profiling and looking for reason of the particular column in output:

http://www.python.org/doc/lib/module-profile.html

#

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)

#

hauser (on February 17, 2008):

I have added modified version of this snippet here: http://www.djangosnippets.org/snippets/605/

#

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 .

#

(Forgotten your password?)

You may use Markdown syntax here, but raw HTML will be removed.