1 # Original version taken from http://www.djangosnippets.org/snippets/186/
2 # Original author: udfalkso
3 # Modified by: Shwagroo Team
14 from django.conf import settings
15 from django.db import connection
18 words_re = re.compile(r'\s+')
21 re.compile("^.*/django/[^/]+"),
22 re.compile("^(.*)/[^/]+$"), # extract module path
23 re.compile(".*"), # catch strange entries
27 class ProfileMiddleware(object):
29 Displays hotshot profiling for any view.
30 http://yoursite.com/yourview/?prof
32 Add the "prof" key to query string by appending ?prof (or &prof=)
33 and you'll see the profiling results in your browser.
34 It's set up to only be available in django's debug mode, is available for superuser otherwise,
35 but you really shouldn't add this middleware to any production configuration.
37 WARNING: It uses hotshot profiler which is not thread safe.
39 def process_request(self, request):
40 if (settings.DEBUG or request.user.is_superuser) and 'prof' in request.GET:
41 connection.queries = []
42 self.tmpfile = tempfile.mktemp()
43 self.prof = hotshot.Profile(self.tmpfile)
45 def process_view(self, request, callback, callback_args, callback_kwargs):
46 if (settings.DEBUG or request.user.is_superuser) and 'prof' in request.GET:
47 return self.prof.runcall(callback, request, *callback_args, **callback_kwargs)
49 def get_group(self, file):
50 for g in group_prefix_re:
51 name = g.findall(file)
55 def get_summary(self, results_dict, sum):
56 list = [(item[1], item[0]) for item in results_dict.items()]
57 list.sort(reverse=True)
66 res += "%4.1f%% %7.3f %s\n" % (foo, item[0], item[1])
70 def summary_for_files(self, stats_str):
71 stats_str = stats_str.split("\n")[5:]
79 fields = words_re.split(s)
81 time = float(fields[2])
83 file = fields[6].split(":")[0]
85 if file not in mystats:
89 group = self.get_group(file)
90 if group not in mygroups:
92 mygroups[group] += time
95 " ---- By file ----\n\n" + self.get_summary(mystats, sum) + "\n" + \
96 " ---- By group ---\n\n" + self.get_summary(mygroups, sum) + \
99 def process_response(self, request, response):
100 if (settings.DEBUG or request.user.is_superuser) and 'prof' in request.GET:
104 old_stdout = sys.stdout
107 stats = hotshot.stats.load(self.tmpfile)
108 stats.sort_stats('time', 'calls')
111 sys.stdout = old_stdout
112 stats_str = out.getvalue()
114 if response and response.content and stats_str:
115 response.content = "<pre>" + stats_str + "</pre>"
117 response.content = "\n".join(response.content.split("\n")[:40])
119 response.content += self.summary_for_files(stats_str)
121 os.unlink(self.tmpfile)
123 response.content += '\n%d SQL Queries:\n' % len(connection.queries)
124 response.content += pprint.pformat(connection.queries)