<s> import cProfile <EOL> import hotshot <EOL> import hotshot . stats <EOL> import pstats <EOL> import sys <EOL> import tempfile <EOL> from cStringIO import StringIO <EOL> def profile_this ( fn ) : <EOL> def profiled_fn ( * args , ** kwargs ) : <EOL> filepath = "<STR_LIT>" % fn . __name__ <EOL> prof = cProfile . Profile ( ) <EOL> ret = prof . runcall ( fn , * args , ** kwargs ) <EOL> print ( "<STR_LIT>" % filepath ) <EOL> prof . dump_stats ( filepath ) <EOL> print ( "<STR_LIT>" ) <EOL> stats = pstats . Stats ( filepath ) <EOL> stats . sort_stats ( '<STR_LIT>' ) <EOL> stats . print_stats ( ) <EOL> return ret <EOL> return profiled_fn <EOL> class BaseMiddleware ( object ) : <EOL> query_param = None <EOL> def show_profile ( self , request ) : <EOL> return self . query_param in request . GET <EOL> def process_request ( self , request ) : <EOL> if self . show_profile ( request ) : <EOL> if '<STR_LIT>' in request . GET : <EOL> self . tmpfile = open ( '<STR_LIT>' , '<STR_LIT:w>' ) <EOL> else : <EOL> self . tmpfile = tempfile . NamedTemporaryFile ( ) <EOL> self . profile = self . profiler ( ) <EOL> def profiler ( self ) : <EOL> return None <EOL> def process_view ( self , request , callback , callback_args , callback_kwargs ) : <EOL> if self . show_profile ( request ) : <EOL> return self . profile . runcall ( <EOL> callback , request , * callback_args , ** callback_kwargs ) <EOL> def process_response ( self , request , response ) : <EOL> if self . show_profile ( request ) : <EOL> stats = self . stats ( ) <EOL> if '<STR_LIT>' in request . GET : <EOL> stats . strip_dirs ( ) <EOL> if '<STR_LIT>' in request . GET : <EOL> stats . sort_stats ( * request . GET [ '<STR_LIT>' ] . split ( '<STR_LIT:U+002C>' ) ) <EOL> else : <EOL> stats . sort_stats ( '<STR_LIT:time>' , '<STR_LIT>' ) <EOL> old_stdout = sys . stdout <EOL> out = StringIO ( ) <EOL> sys . stdout = out <EOL> stats . print_stats ( ) <EOL> stats_str = out . getvalue ( ) <EOL> sys . stdout . close ( ) <EOL> sys . stdout = old_stdout <EOL> if response and response . content and stats_str : <EOL> response . content = "<STR_LIT>" + stats_str + "<STR_LIT>" <EOL> return response <EOL> class ProfileMiddleware ( BaseMiddleware ) : <EOL> query_param = '<STR_LIT>' <EOL> def profiler ( self ) : <EOL> return cProfile . Profile ( ) <EOL> def stats ( self ) : <EOL> self . profile . dump_stats ( self . tmpfile . name ) <EOL> return pstats . Stats ( self . tmpfile . name ) <EOL> class HotshotMiddleware ( BaseMiddleware ) : <EOL> """<STR_LIT>""" <EOL> query_param = '<STR_LIT>' <EOL> def profiler ( self ) : <EOL> return hotshot . Profile ( self . tmpfile . name ) <EOL> def stats ( self ) : <EOL> self . profile . close ( ) <EOL> return hotshot . stats . load ( self . tmpfile . name ) </s>
