Created
June 26, 2018 08:16
-
-
Save gzcf/fd149471cba9dd0c240447fa2e80d791 to your computer and use it in GitHub Desktop.
Using cProfile module to profile django views' performances.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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