Skip to content

Commit f1a3045

Browse files
committed
Adjust toolbar insertion code to avoid .lower().
Fix #531.
1 parent 9dc89cc commit f1a3045

File tree

1 file changed

+14
-7
lines changed

1 file changed

+14
-7
lines changed

debug_toolbar/middleware.py

+14-7
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
from __future__ import absolute_import, unicode_literals
66

7+
import re
78
import threading
89

910
from django.conf import settings
@@ -106,13 +107,19 @@ def process_response(self, request, response):
106107

107108
# Insert the toolbar in the response.
108109
content = force_text(response.content, encoding=settings.DEFAULT_CHARSET)
109-
try:
110-
insert_at = content.lower().rindex(dt_settings.CONFIG['INSERT_BEFORE'].lower())
111-
except ValueError:
112-
pass
113-
else:
114-
toolbar_content = toolbar.render_toolbar()
115-
response.content = content[:insert_at] + toolbar_content + content[insert_at:]
110+
insert_before = dt_settings.CONFIG['INSERT_BEFORE']
111+
try: # Python >= 2.7
112+
pattern = re.escape(insert_before)
113+
bits = re.split(pattern, content, flags=re.IGNORECASE)
114+
except TypeError: # Python < 2.7
115+
pattern = '(.+?)(%s|$)' % re.escape(insert_before)
116+
matches = re.findall(pattern, content, flags=re.DOTALL | re.IGNORECASE)
117+
bits = [m[0] for m in matches if m[1] == insert_before]
118+
# When the body ends with a newline, there's two trailing groups.
119+
bits.append(''.join(m[0] for m in matches if m[1] == ''))
120+
if len(bits) > 1:
121+
bits[-2] += toolbar.render_toolbar()
122+
response.content = insert_before.join(bits)
116123
if response.get('Content-Length', None):
117124
response['Content-Length'] = len(response.content)
118125
return response

0 commit comments

Comments
 (0)