Skip to content

Instantly share code, notes, and snippets.

@stringfellow
Created March 17, 2016 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stringfellow/37d6c53969a27201254e to your computer and use it in GitHub Desktop.
Save stringfellow/37d6c53969a27201254e to your computer and use it in GitHub Desktop.
Simple Django profiling middleware
# -*- 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