@@ -41,6 +41,8 @@ class ProfilerMiddleware(MiddlewareMixin):
41
41
This is adapted from an example found here:
42
42
http://www.slideshare.net/zeeg/django-con-high-performance-django-presentation.
43
43
"""
44
+ PROFILER_REQUEST_ATTR_NAME = '_django_cprofile_middleware_profiler'
45
+
44
46
def can (self , request ):
45
47
requires_staff = getattr (
46
48
settings , "DJANGO_CPROFILE_MIDDLEWARE_REQUIRE_STAFF" , True )
@@ -52,31 +54,33 @@ def can(self, request):
52
54
53
55
def process_view (self , request , callback , callback_args , callback_kwargs ):
54
56
if self .can (request ):
55
- self .profiler = profile .Profile ()
57
+ profiler = profile .Profile ()
58
+ setattr (request , self .PROFILER_REQUEST_ATTR_NAME , profiler )
56
59
args = (request ,) + callback_args
57
60
try :
58
- return self . profiler .runcall (
61
+ return profiler .runcall (
59
62
callback , * args , ** callback_kwargs )
60
63
except Exception :
61
64
# we want the process_exception middleware to fire
62
65
# https://code.djangoproject.com/ticket/12250
63
66
return
64
67
65
68
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 ()
68
72
if 'download' in request .GET :
69
73
import marshal
70
74
71
- output = marshal .dumps (self . profiler .stats )
75
+ output = marshal .dumps (profiler .stats )
72
76
response = HttpResponse (
73
77
output , content_type = 'application/octet-stream' )
74
78
response ['Content-Disposition' ] = 'attachment;' \
75
79
' filename=view.prof'
76
80
response ['Content-Length' ] = len (output )
77
81
else :
78
82
io = StringIO ()
79
- stats = pstats .Stats (self . profiler , stream = io )
83
+ stats = pstats .Stats (profiler , stream = io )
80
84
81
85
stats .strip_dirs ().sort_stats (request .GET .get ('sort' , 'time' ))
82
86
stats .print_stats (int (request .GET .get ('count' , 100 )))
0 commit comments