1# Copyright (c) 2012-2016 Seafile Ltd.
2"""
3The MIT License (MIT)
4
5Copyright (c) 2013 Omar Bohsali
6
7Permission is hereby granted, free of charge, to any person obtaining a copy
8of this software and associated documentation files (the "Software"), to deal
9in the Software without restriction, including without limitation the rights
10to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11copies of the Software, and to permit persons to whom the Software is
12furnished to do so, subject to the following conditions:
13
14The above copyright notice and this permission notice shall be included in
15all copies or substantial portions of the Software.
16
17THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23THE SOFTWARE.
24"""
25
26try:
27    import cProfile as profile
28except ImportError:
29    from . import profile
30
31import pstats
32from io import StringIO
33from django.conf import settings
34from django.utils.deprecation import MiddlewareMixin
35
36class ProfilerMiddleware(MiddlewareMixin):
37    """
38    Simple profile middleware to profile django views. To run it, add ?prof to
39    the URL like this:
40
41        http://localhost:8000/view/?__prof__=true
42
43    Optionally pass the following to modify the output:
44
45    ?sort => Sort the output by a given metric. Default is time.
46        See http://docs.python.org/2/library/profile.html#pstats.Stats.sort_stats
47        for all sort options.
48
49        quick reference:
50        - time: sort by function execution time
51        - cum: the cumulative time spent in this and all subfunctions (from invocation till exit). This figure is accurate even for recursive functions.
52
53    ?count => The number of rows to display. Default is 100.
54
55    ?fullpath=<true|false> default false. True to show full path of the source file of each function
56
57    ?callee=<true|false> default false. True to show the time of a function spent on its sub function.
58
59    This is adapted from an example found here:
60    http://www.slideshare.net/zeeg/django-con-high-performance-django-presentation.
61    """
62    def can(self, request):
63        return settings.DEBUG and request.GET.get('__prof__', False) == 'true'
64
65    def process_view(self, request, callback, callback_args, callback_kwargs):
66        if self.can(request):
67            self.profiler = profile.Profile()
68            args = (request,) + callback_args
69            return self.profiler.runcall(callback, *args, **callback_kwargs)
70
71    def process_response(self, request, response):
72        if self.can(request):
73            self.profiler.create_stats()
74            io = StringIO()
75            stats = pstats.Stats(self.profiler, stream=io)
76            if not request.GET.get('fullpath', False):
77                stats.strip_dirs()
78
79            stats.sort_stats(request.GET.get('sort', 'time'))
80
81            if request.GET.get('callee', False):
82                stats.print_callees()
83
84            stats.print_stats(int(request.GET.get('count', 100)))
85            response.content = '<pre>%s</pre>' % io.getvalue()
86        return response
87