Skip to content

Commit 791fbfe

Browse files
committed
Set the profiler instance on the request, not the middleware
This fix was proficed by ahumeau in pull request omarish#23 of the original repo.
1 parent 80e27f3 commit 791fbfe

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

django_cprofile_middleware/middleware.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,8 @@ class ProfilerMiddleware(MiddlewareMixin):
4141
This is adapted from an example found here:
4242
http://www.slideshare.net/zeeg/django-con-high-performance-django-presentation.
4343
"""
44+
PROFILER_REQUEST_ATTR_NAME = '_django_cprofile_middleware_profiler'
45+
4446
def can(self, request):
4547
requires_staff = getattr(
4648
settings, "DJANGO_CPROFILE_MIDDLEWARE_REQUIRE_STAFF", True)
@@ -52,31 +54,33 @@ def can(self, request):
5254

5355
def process_view(self, request, callback, callback_args, callback_kwargs):
5456
if self.can(request):
55-
self.profiler = profile.Profile()
57+
profiler = profile.Profile()
58+
setattr(request, self.PROFILER_REQUEST_ATTR_NAME, profiler)
5659
args = (request,) + callback_args
5760
try:
58-
return self.profiler.runcall(
61+
return profiler.runcall(
5962
callback, *args, **callback_kwargs)
6063
except Exception:
6164
# we want the process_exception middleware to fire
6265
# https://code.djangoproject.com/ticket/12250
6366
return
6467

6568
def process_response(self, request, response):
66-
if self.can(request):
67-
self.profiler.create_stats()
69+
if hasattr(request, self.PROFILER_REQUEST_ATTR_NAME):
70+
profiler = getattr(request, self.PROFILER_REQUEST_ATTR_NAME)
71+
profiler.create_stats()
6872
if 'download' in request.GET:
6973
import marshal
7074

71-
output = marshal.dumps(self.profiler.stats)
75+
output = marshal.dumps(profiler.stats)
7276
response = HttpResponse(
7377
output, content_type='application/octet-stream')
7478
response['Content-Disposition'] = 'attachment;' \
7579
' filename=view.prof'
7680
response['Content-Length'] = len(output)
7781
else:
7882
io = StringIO()
79-
stats = pstats.Stats(self.profiler, stream=io)
83+
stats = pstats.Stats(profiler, stream=io)
8084

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

0 commit comments

Comments
 (0)