Code layout change.
[wolnelektury.git] / src / wolnelektury / middleware.py
1 # Orignal version taken from http://www.djangosnippets.org/snippets/186/
2 # Original author: udfalkso
3 # Modified by: Shwagroo Team
4
5 import sys
6 import os
7 import re
8 import hotshot, hotshot.stats
9 import tempfile
10 import StringIO
11 import pprint
12
13 from django.conf import settings
14 from django.db import connection
15
16
17 words_re = re.compile( r'\s+' )
18
19 group_prefix_re = [
20     re.compile( "^.*/django/[^/]+" ),
21     re.compile( "^(.*)/[^/]+$" ), # extract module path
22     re.compile( ".*" ),           # catch strange entries
23 ]
24
25
26 class ProfileMiddleware(object):
27     """
28     Displays hotshot profiling for any view.
29     http://yoursite.com/yourview/?prof
30
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.
35
36     WARNING: It uses hotshot profiler which is not thread safe.
37     """
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)
43
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)
47
48     def get_group(self, file):
49         for g in group_prefix_re:
50             name = g.findall( file )
51             if name:
52                 return name[0]
53
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 )
57         list = list[:40]
58
59         res = "      tottime\n"
60         for item in list:
61             if sum == 0:
62                 foo = 0
63             else:
64                 foo = 100*item[0]/sum
65             res += "%4.1f%% %7.3f %s\n" % (foo, item[0], item[1] )
66
67         return res
68
69     def summary_for_files(self, stats_str):
70         stats_str = stats_str.split("\n")[5:]
71
72         mystats = {}
73         mygroups = {}
74
75         sum = 0
76
77         for s in stats_str:
78             fields = words_re.split(s);
79             if len(fields) == 7:
80                 time = float(fields[2])
81                 sum += time
82                 file = fields[6].split(":")[0]
83
84                 if not file in mystats:
85                     mystats[file] = 0
86                 mystats[file] += time
87
88                 group = self.get_group(file)
89                 if not group in mygroups:
90                     mygroups[ group ] = 0
91                 mygroups[ group ] += time
92
93         return "<pre>" + \
94                " ---- By file ----\n\n" + self.get_summary(mystats,sum) + "\n" + \
95                " ---- By group ---\n\n" + self.get_summary(mygroups,sum) + \
96                "</pre>"
97
98     def process_response(self, request, response):
99         if (settings.DEBUG or request.user.is_superuser) and request.GET.has_key('prof'):
100             self.prof.close()
101
102             out = StringIO.StringIO()
103             old_stdout = sys.stdout
104             sys.stdout = out
105
106             stats = hotshot.stats.load(self.tmpfile)
107             stats.sort_stats('time', 'calls')
108             stats.print_stats()
109
110             sys.stdout = old_stdout
111             stats_str = out.getvalue()
112
113             if response and response.content and stats_str:
114                 response.content = "<pre>" + stats_str + "</pre>"
115
116             response.content = "\n".join(response.content.split("\n")[:40])
117
118             response.content += self.summary_for_files(stats_str)
119
120             os.unlink(self.tmpfile)
121
122             response.content += '\n%d SQL Queries:\n' % len(connection.queries)
123             response.content += pprint.pformat(connection.queries)
124
125         return response
126