2 Debug Toolbar middleware
5 from django.conf import settings
6 from django.utils.encoding import smart_str
7 from debug_toolbar.toolbar.loader import DebugToolbar
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)
13 class DebugToolbarMiddleware(object):
15 Middleware to set up Debug Toolbar on incoming request and render toolbar
19 self.debug_toolbar = None
21 def show_toolbar(self, request):
22 if not settings.DEBUG:
24 if not request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
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)
37 if debug == panel.name:
38 response = panel.process_ajax(request)
40 response.skip_debug_response = True
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)
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`
60 response.content = _END_BODY_RE.sub(smart_str('<body>' + self.debug_toolbar.render_toolbar()), response.content)