Last active
May 30, 2017 08:35
-
-
Save cristianca/846e0bc0b9a03bd711cc48ac1b26dcfe to your computer and use it in GitHub Desktop.
Profile Middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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