1 # Orignal version taken from http://www.djangosnippets.org/snippets/186/
2 # Original author: udfalkso
3 # Modified by: Shwagroo Team
8 import hotshot, hotshot.stats
13 from django.conf import settings
14 from django.db import connection
17 words_re = re.compile( r'\s+' )
20 re.compile( "^.*/django/[^/]+" ),
21 re.compile( "^(.*)/[^/]+$" ), # extract module path
22 re.compile( ".*" ), # catch strange entries
26 class ProfileMiddleware(object):
28 Displays hotshot profiling for any view.
29 http://yoursite.com/yourview/?prof
31 Add the "prof" key to query string by appending ?prof (or &prof=)
32 and you'll see the profiling results in your browser.
33 It's set up to only be available in django's debug mode, is available for superuser otherwise,
34 but you really shouldn't add this middleware to any production configuration.
36 WARNING: It uses hotshot profiler which is not thread safe.
38 def process_request(self, request):
39 if (settings.DEBUG or request.user.is_superuser) and request.GET.has_key('prof'):
40 connection.queries = []
41 self.tmpfile = tempfile.mktemp()
42 self.prof = hotshot.Profile(self.tmpfile)
44 def process_view(self, request, callback, callback_args, callback_kwargs):
45 if (settings.DEBUG or request.user.is_superuser) and request.GET.has_key('prof'):
46 return self.prof.runcall(callback, request, *callback_args, **callback_kwargs)
48 def get_group(self, file):
49 for g in group_prefix_re:
50 name = g.findall( file )
54 def get_summary(self, results_dict, sum):
55 list = [ (item[1], item[0]) for item in results_dict.items() ]
56 list.sort( reverse = True )
65 res += "%4.1f%% %7.3f %s\n" % (foo, item[0], item[1] )
69 def summary_for_files(self, stats_str):
70 stats_str = stats_str.split("\n")[5:]
78 fields = words_re.split(s);
80 time = float(fields[2])
82 file = fields[6].split(":")[0]
84 if not file in mystats:
88 group = self.get_group(file)
89 if not group in mygroups:
91 mygroups[ group ] += time
94 " ---- By file ----\n\n" + self.get_summary(mystats,sum) + "\n" + \
95 " ---- By group ---\n\n" + self.get_summary(mygroups,sum) + \
98 def process_response(self, request, response):
99 if (settings.DEBUG or request.user.is_superuser) and request.GET.has_key('prof'):
102 out = StringIO.StringIO()
103 old_stdout = sys.stdout
106 stats = hotshot.stats.load(self.tmpfile)
107 stats.sort_stats('time', 'calls')
110 sys.stdout = old_stdout
111 stats_str = out.getvalue()
113 if response and response.content and stats_str:
114 response.content = "<pre>" + stats_str + "</pre>"
116 response.content = "\n".join(response.content.split("\n")[:40])
118 response.content += self.summary_for_files(stats_str)
120 os.unlink(self.tmpfile)
122 response.content += '\n%d SQL Queries:\n' % len(connection.queries)
123 response.content += pprint.pformat(connection.queries)