diff options
| author | Aymeric Augustin | 2013-11-18 08:17:15 +0100 |
|---|---|---|
| committer | Aymeric Augustin | 2013-11-18 08:17:15 +0100 |
| commit | 7697c93692cb251acec174e91431f6aa2b1ebce5 (patch) | |
| tree | 148e58cb5b8ab847a6ed70ddaa0b051cbf2da688 | |
| parent | bb8694f5cf676c4b13d7c4af59a33f5e6eeaf363 (diff) | |
| download | django-debug-toolbar-7697c93692cb251acec174e91431f6aa2b1ebce5.tar.bz2 | |
Decode source code with the declared encoding.
Fix #228.
| -rw-r--r-- | debug_toolbar/utils.py | 20 |
1 files changed, 17 insertions, 3 deletions
diff --git a/debug_toolbar/utils.py b/debug_toolbar/utils.py index c94e19c..d7197b6 100644 --- a/debug_toolbar/utils.py +++ b/debug_toolbar/utils.py @@ -2,9 +2,10 @@ from __future__ import unicode_literals import inspect import os.path -import django +import re import sys +import django from django.core.exceptions import ImproperlyConfigured from django.utils.encoding import force_text from django.utils.html import escape @@ -160,14 +161,27 @@ def getframeinfo(frame, context=1): try: lines, lnum = inspect.findsource(frame) except Exception: # findsource raises platform-dependant exceptions - lines = index = None + first_lines = lines = index = None else: start = max(start, 1) start = max(0, min(start, len(lines) - context)) + first_lines = lines[:2] lines = lines[start:(start + context)] index = lineno - 1 - start else: - lines = index = None + first_lines = lines = index = None + + # Code taken from Django's ExceptionReporter._get_lines_from_file + if first_lines and isinstance(first_lines[0], bytes): + encoding = 'ascii' + for line in first_lines[:2]: + # File coding may be specified. Match pattern from PEP-263 + # (http://www.python.org/dev/peps/pep-0263/) + match = re.search(br'coding[:=]\s*([-\w.]+)', line) + if match: + encoding = match.group(1).decode('ascii') + break + lines = [line.decode(encoding, 'replace') for line in lines] if hasattr(inspect, 'Traceback'): return inspect.Traceback(filename, lineno, frame.f_code.co_name, lines, index) |
