2ef7f1b72140fa3f633b8b25ff7a97115259b678
[wolnelektury.git] / apps / debug_toolbar / middleware.py
1 """
2 Debug Toolbar middleware
3 """
4 import re
5 from django.conf import settings
6 from django.utils.encoding import smart_str
7 from debug_toolbar.toolbar.loader import DebugToolbar
8
9 _HTML_TYPES = ('text/html', 'application/xhtml+xml')
10 _END_HEAD_RE = re.compile(r'</head>', re.IGNORECASE)
11 _END_BODY_RE = re.compile(r'<body[^<]*>', re.IGNORECASE)
12
13 class DebugToolbarMiddleware(object):
14     """
15     Middleware to set up Debug Toolbar on incoming request and render toolbar
16     on outgoing response.
17     """
18     def __init__(self):
19         self.debug_toolbar = None
20
21     def show_toolbar(self, request):
22         if not settings.DEBUG:
23             return False
24         if not request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
25             return False
26         return True
27
28     def process_request(self, request):
29         if self.show_toolbar(request):
30             self.debug_toolbar = DebugToolbar(request)
31             self.debug_toolbar.load_panels()
32             debug = request.GET.get('djDebug')
33             # kinda ugly, needs changes to the loader to optimize
34             for panel in self.debug_toolbar.panels:
35                 response = panel.process_request(request)
36                 if not response:
37                     if debug == panel.name:
38                         response = panel.process_ajax(request)
39                 if response:
40                     response.skip_debug_response = True
41                     return response
42
43     def process_view(self, request, callback, callback_args, callback_kwargs):
44         if self.show_toolbar(request):
45             for panel in self.debug_toolbar.panels:
46                 cb = panel.process_view(request, callback, callback_args, callback_kwargs)
47                 if cb:
48                     callback = cb
49             return callback
50
51     def process_response(self, request, response):
52         if self.show_toolbar(request) and not getattr(response, 'skip_debug_response', False):
53             if response['Content-Type'].split(';')[0] in _HTML_TYPES and not request.is_ajax():
54                 # Saving this here in case we ever need to inject into <head>
55                 #response.content = _END_HEAD_RE.sub(smart_str(self.debug_toolbar.render_styles() + "%s" % match.group()), response.content)
56                 for panel in self.debug_toolbar.panels:
57                     nr = panel.process_response(request, response)
58                     # Incase someone forgets `return response`
59                     if nr: response = nr
60                 response.content = _END_BODY_RE.sub(smart_str('<body>' + self.debug_toolbar.render_toolbar()), response.content)
61         return response