Mercurial > kallithea
annotate rhodecode/lib/profiler.py @ 2060:572855f7a392 beta
reverted git fix as it broke pushing
author | Marcin Kuzminski <marcin@python-works.com> |
---|---|
date | Tue, 28 Feb 2012 07:08:42 +0200 |
parents | c1516b35f91d |
children | 2c2bdaeca912 |
rev | line source |
---|---|
15 | 1 from __future__ import with_statement |
2 | |
3 import cProfile | |
4 import pstats | |
5 import cgi | |
6 import pprint | |
7 import threading | |
8 | |
9 from StringIO import StringIO | |
10 | |
1307 | 11 |
15 | 12 class ProfilingMiddleware(object): |
13 def __init__(self, app): | |
14 self.lock = threading.Lock() | |
15 self.app = app | |
1203
6832ef664673
source code cleanup: remove trailing white space, normalize file endings
Marcin Kuzminski <marcin@python-works.com>
parents:
547
diff
changeset
|
16 |
15 | 17 def __call__(self, environ, start_response): |
18 with self.lock: | |
19 profiler = cProfile.Profile() | |
1307 | 20 |
15 | 21 def run_app(*a, **kw): |
22 self.response = self.app(environ, start_response) | |
23 | |
24 profiler.runcall(run_app, environ, start_response) | |
25 | |
26 profiler.snapshot_stats() | |
27 | |
28 stats = pstats.Stats(profiler) | |
29 stats.sort_stats('cumulative') | |
30 | |
31 # Redirect output | |
32 out = StringIO() | |
33 stats.stream = out | |
34 | |
35 stats.print_stats() | |
36 | |
37 resp = ''.join(self.response) | |
38 | |
39 # Lets at least only put this on html-like responses. | |
40 if resp.strip().startswith('<'): | |
41 ## The profiling info is just appended to the response. | |
42 ## Browsers don't mind this. | |
1307 | 43 resp += ('<pre style="text-align:left; ' |
44 'border-top: 4px dashed red; padding: 1em;">') | |
15 | 45 resp += cgi.escape(out.getvalue(), True) |
1203
6832ef664673
source code cleanup: remove trailing white space, normalize file endings
Marcin Kuzminski <marcin@python-works.com>
parents:
547
diff
changeset
|
46 |
15 | 47 output = StringIO() |
48 pprint.pprint(environ, output, depth=3) | |
1203
6832ef664673
source code cleanup: remove trailing white space, normalize file endings
Marcin Kuzminski <marcin@python-works.com>
parents:
547
diff
changeset
|
49 |
15 | 50 resp += cgi.escape(output.getvalue(), True) |
51 resp += '</pre>' | |
1203
6832ef664673
source code cleanup: remove trailing white space, normalize file endings
Marcin Kuzminski <marcin@python-works.com>
parents:
547
diff
changeset
|
52 |
15 | 53 return resp |