Skip to content

Instantly share code, notes, and snippets.

@cristianca
Last active May 30, 2017 08:35
Show Gist options
  • Save cristianca/846e0bc0b9a03bd711cc48ac1b26dcfe to your computer and use it in GitHub Desktop.
Save cristianca/846e0bc0b9a03bd711cc48ac1b26dcfe to your computer and use it in GitHub Desktop.
Profile Middleware
import logging
try:
import cProfile as profile
except ImportError:
import profile
import pstats
logger = logging.getLogger(__name__)
class ProfileMiddleware(object):
# Simple middleware to profile the requests
def __init__(self):
self.profiler = None
def process_view(self, request, callback, callback_args, callback_kwargs):
self.profiler = profile.Profile()
args = (request,) + callback_args
return self.profiler.runcall(callback, *args, **callback_kwargs)
def process_response(self, request, response):
if not self.profiler:
return response
# create the stats
self.profiler.create_stats()
stats = pstats.Stats(self.profiler)
logger.debug('[PROFILE] {0} in {1} seconds'.format(request.path, stats.total_tt))
# print more infos
# stats.strip_dirs().sort_stats(request.GET.get('sort', 'time'))
# stats.print_stats(int(request.GET.get('count', 100)))
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment