错误报告期间的Django UnicodeDecodeError

时间:2019-05-24 08:21:35

标签: python django error-reporting

错误报告不断崩溃。在回溯中,我首先得到实际错误,然后多次相同。

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/var/www/exc2-backend/.venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/var/www/exc2-backend/.venv/lib/python3.6/site-packages/django/utils/deprecation.py", line 94, in __call__
    response = response or self.get_response(request)
  File "/var/www/exc2-backend/.venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 36, in inner
    response = response_for_exception(request, exc)
  File "/var/www/exc2-backend/.venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 90, in response_for_exception
    response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
  File "/var/www/exc2-backend/.venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 125, in handle_uncaught_exception
    return debug.technical_500_response(request, *exc_info)
  File "/var/www/exc2-backend/.venv/lib/python3.6/site-packages/django/views/debug.py", line 94, in technical_500_response
    html = reporter.get_traceback_html()
  File "/var/www/exc2-backend/.venv/lib/python3.6/site-packages/django/views/debug.py", line 332, in get_traceback_html
    t = DEBUG_ENGINE.from_string(fh.read())
  File "/var/www/exc2-backend/.venv/lib/python3.6/encodings/ascii.py", line 26, in decode
    return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 9735: ordinal not in range(128)

我正在使用Python3.6Django==2.2。我不知道UnicodeDecodeError的来源。

在生产服务器上运行

from django.test.client import RequestFactory
import sys
from django.views.debug import ExceptionReporter

request = RequestFactory().get('/dummy')
exc_info = sys.exc_info()
reporter = ExceptionReporter(request, is_email=True, *exc_info)
reporter.get_traceback_html()

工作正常而不会崩溃。

我正在使用以下命令运行带有gunicorn的网站

/var/www/exc2-backend/.venv/bin/gunicorn exc2_backend.wsgi --name "exc2_backend" --workers=4 --bind=0.0.0.0:8000 --user="www-data" --group="www-data"

我缩小了问题的范围,在这里发生

from django.views.debug import ExceptionReporter, CURRENT_DIR, DEBUG_ENGINE
from pathlib import Path

with Path(CURRENT_DIR, 'templates', 'technical_500.html').open() as fh:
    data = fh.read()

如果我更改为Path(...).open(encoding='utf8'),则没有错误。

仅在使用gunicorn运行代码时,shell不会发生错误。

在服务器上,即使通过粗话,sys.getdefaultencoding()也会返回utf-8,但是locale.getpreferredencoding(False)会返回ANSI_X3.4-1968

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我在Gunicorn(fr_FR.UTF8)中设置的语言环境尚未安装在系统上,因此Python会默认使用ANSI_X3.4-1968编码。

解决方案是安装缺少的语言环境:sudo locale-gen fr_FR.UTF-8