Created
March 17, 2016 16:04
-
-
Save stringfellow/37d6c53969a27201254e to your computer and use it in GitHub Desktop.
Simple Django profiling middleware
This file contains hidden or 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
# -*- coding: utf-8 -*- | |
import cProfile | |
import pstats | |
from django.conf import settings | |
class ProfileStatsMiddleware(object): # pragma: no cover | |
"""Super light-weight cProfile/pstats profile middleware.""" | |
def process_request(self, request): | |
"""Just enable the profiler before continuing if set.""" | |
if settings.DEBUG and 'prof' in request.GET: | |
self.pr = cProfile.Profile() | |
self.pr.enable() | |
def process_response(self, request, response): | |
"""Disable the profiler and rewrite the content if set.""" | |
if settings.DEBUG and 'prof' in request.GET: | |
response.content = "" | |
self.pr.disable() | |
sortby = request.GET.get('prof') or 'cumulative' | |
ps = pstats.Stats(self.pr, stream=response).sort_stats(sortby) | |
ps.print_stats() | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment