Login

Profiling Middlware

Author:
udfalkso
Posted:
April 17, 2007
Language:
Python
Version:
.96
Score:
24 (after 24 ratings)

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

  • You should probably use this one instead: http://djangosnippets.org/snippets/2126/

 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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 4 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 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

#

Please login first before commenting.