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