Skip to content

Instantly share code, notes, and snippets.

@gzcf
Created June 26, 2018 08:16
Show Gist options
  • Save gzcf/fd149471cba9dd0c240447fa2e80d791 to your computer and use it in GitHub Desktop.
Save gzcf/fd149471cba9dd0c240447fa2e80d791 to your computer and use it in GitHub Desktop.
Using cProfile module to profile django views' performances.
from django.utils.deprecation import MiddlewareMixin
class ViewProfilerMiddleware(MiddlewareMixin):
def process_request(self, request):
self._pr = cProfile.Profile()
self._pr.enable()
def process_response(self, request, response):
self._pr.disable()
self._pr.dump_stats(os.path.join(self.output_dir, self._path_to_filename(request.path)))
return response
@property
def output_dir(self):
try:
return settings.PROFILER_OUTPUT_DIR
except AttributeError:
return ''
def _path_to_filename(self, path):
return path.strip('/').replace('/', '_')
from django.utils.decorators import decorator_from_middleware
class ViewProfilerMixin(object):
"""
Adds ViewProfilerMixin to any Django View by overriding as_view.
"""
@classmethod
def as_view(cls, *args, **kwargs):
view = super(ViewProfilerMixin, cls).as_view(*args, **kwargs)
view = decorator_from_middleware(ViewProfilerMiddleware)(view)
return view
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment