Skip to content

Commit 7697c93

Browse files
committed
Decode source code with the declared encoding.
Fix #228.
1 parent bb8694f commit 7697c93

File tree

1 file changed

+17
-3
lines changed

1 file changed

+17
-3
lines changed

debug_toolbar/utils.py

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@
22

33
import inspect
44
import os.path
5-
import django
5+
import re
66
import sys
77

8+
import django
89
from django.core.exceptions import ImproperlyConfigured
910
from django.utils.encoding import force_text
1011
from django.utils.html import escape
@@ -160,14 +161,27 @@ def getframeinfo(frame, context=1):
160161
try:
161162
lines, lnum = inspect.findsource(frame)
162163
except Exception: # findsource raises platform-dependant exceptions
163-
lines = index = None
164+
first_lines = lines = index = None
164165
else:
165166
start = max(start, 1)
166167
start = max(0, min(start, len(lines) - context))
168+
first_lines = lines[:2]
167169
lines = lines[start:(start + context)]
168170
index = lineno - 1 - start
169171
else:
170-
lines = index = None
172+
first_lines = lines = index = None
173+
174+
# Code taken from Django's ExceptionReporter._get_lines_from_file
175+
if first_lines and isinstance(first_lines[0], bytes):
176+
encoding = 'ascii'
177+
for line in first_lines[:2]:
178+
# File coding may be specified. Match pattern from PEP-263
179+
# (http://www.python.org/dev/peps/pep-0263/)
180+
match = re.search(br'coding[:=]\s*([-\w.]+)', line)
181+
if match:
182+
encoding = match.group(1).decode('ascii')
183+
break
184+
lines = [line.decode(encoding, 'replace') for line in lines]
171185

172186
if hasattr(inspect, 'Traceback'):
173187
return inspect.Traceback(filename, lineno, frame.f_code.co_name, lines, index)

0 commit comments

Comments
 (0)