|
4 | 4 |
|
5 | 5 | from __future__ import absolute_import, unicode_literals
|
6 | 6 |
|
| 7 | +import re |
7 | 8 | import threading
|
8 | 9 |
|
9 | 10 | from django.conf import settings
|
@@ -106,13 +107,19 @@ def process_response(self, request, response):
|
106 | 107 |
|
107 | 108 | # Insert the toolbar in the response.
|
108 | 109 | 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) |
116 | 123 | if response.get('Content-Length', None):
|
117 | 124 | response['Content-Length'] = len(response.content)
|
118 | 125 | return response
|
0 commit comments