5 from django
.conf
import settings
6 from cStringIO
import StringIO
8 class ProfileMiddleware(object):
10 Displays hotshot profiling for any view.
11 http://yoursite.com/yourview/?prof
13 Add the "prof" key to query string by appending ?prof (or &prof=)
14 and you'll see the profiling results in your browser.
15 It's set up to only be available in django's debug mode,
16 but you really shouldn't add this middleware to any production configuration.
17 * Only tested on Linux
19 def process_request(self
, request
):
20 if settings
.DEBUG
and request
.GET
.has_key('prof'):
21 self
.tmpfile
= tempfile
.NamedTemporaryFile()
22 self
.prof
= hotshot
.Profile(self
.tmpfile
.name
)
24 def process_view(self
, request
, callback
, callback_args
, callback_kwargs
):
25 if settings
.DEBUG
and request
.GET
.has_key('prof'):
26 return self
.prof
.runcall(callback
, request
, *callback_args
, **callback_kwargs
)
28 def process_response(self
, request
, response
):
29 if settings
.DEBUG
and request
.GET
.has_key('prof'):
33 old_stdout
= sys
.stdout
36 stats
= hotshot
.stats
.load(self
.tmpfile
.name
)
38 stats
.sort_stats('cumulative', 'calls')
41 sys
.stdout
= old_stdout
42 stats_str
= out
.getvalue()
44 if response
and response
.content
and stats_str
:
45 response
.content
= "<pre>" + stats_str
+ "</pre>"