Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Set the profiler instance on the request, not the middleware #23

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions django_cprofile_middleware/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,37 +40,41 @@ class ProfilerMiddleware(MiddlewareMixin):
This is adapted from an example found here:
http://www.slideshare.net/zeeg/django-con-high-performance-django-presentation.
"""
PROFILER_REQUEST_ATTR_NAME = '_django_cprofile_middleware_profiler'

def can(self, request):
return settings.DEBUG and 'prof' in request.GET and \
request.user is not None and request.user.is_staff

def process_view(self, request, callback, callback_args, callback_kwargs):
if self.can(request):
self.profiler = profile.Profile()
profiler = profile.Profile()
setattr(request, self.PROFILER_REQUEST_ATTR_NAME, profiler)
args = (request,) + callback_args
try:
return self.profiler.runcall(
return profiler.runcall(
callback, *args, **callback_kwargs)
except Exception:
# we want the process_exception middleware to fire
# https://code.djangoproject.com/ticket/12250
return

def process_response(self, request, response):
if self.can(request):
self.profiler.create_stats()
if hasattr(request, self.PROFILER_REQUEST_ATTR_NAME):
profiler = getattr(request, self.PROFILER_REQUEST_ATTR_NAME)
profiler.create_stats()
if 'download' in request.GET:
import marshal

output = marshal.dumps(self.profiler.stats)
output = marshal.dumps(profiler.stats)
response = HttpResponse(
output, content_type='application/octet-stream')
response['Content-Disposition'] = 'attachment;' \
' filename=view.prof'
response['Content-Length'] = len(output)
else:
io = StringIO()
stats = pstats.Stats(self.profiler, stream=io)
stats = pstats.Stats(profiler, stream=io)

stats.strip_dirs().sort_stats(request.GET.get('sort', 'time'))
stats.print_stats(int(request.GET.get('count', 100)))
Expand Down