【发布时间】:2017-12-23 21:21:40
【问题描述】:
我正在编写一个 Django 应用程序,它将 Unicode 打印到 stdout。它在开发服务器上完美运行,但使用 Apache 和 modwsgi 我得到UnicodeEncodeError: 'ascii' codec can't encode characters ...。
因此,stdout 编码被强制为 ASCII。我找到了许多解决方案,所有这些似乎都应该根据文档工作,但没有一个对我有用:
我尝试使用
SetEnv指令将PYTHONIOENCODING变量设置为utf-8。我还尝试使用
SetEnv和PassEnv将LANG、LC_ALL、LC_CTYPE设置为en_US.UTF-8。由于我的 Apache 服务器在
systemd下运行,我尝试使用服务文件中的Environment=指令设置变量。最后,我尝试将
lang=en_US.UTF-8 locale=en_US.UTF-8添加到WSGIDaemonProcess指令中。
在环境中可以看到变量(例如反映在调试模式下的 Django 错误页面上),但错误仍然存在。
为什么这些东西不起作用,我该怎么办?在 Apache 外部正常工作的代码中覆盖 stdout 或手动编码所有内容都不是正确的方法。
错误发生在普通的print 语句中。这是引发错误的整个视图:
def test(request):
import locale
print locale.getdefaultlocale()
print locale.getpreferredencoding()
s = u'привет'
print s
return s
Apache 错误日志:
('en_US', 'UTF-8')
UTF-8
Internal Server Error: /app/testview/
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response
response = self._get_response(request)
File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/web/my_site/my_app/views.py", line 964, in test
print s
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128)
当我打印sys.stdout 本身时,我发现它实际上是一个mod_wsgi.Log 对象。在 WSGI 文件中,我所有的日志记录是:
logging.basicConfig(stream=sys.stderr)
版本: 蟒蛇2.7.14, 阿帕奇 2.4.29, mod_wsgi 4.5.20 在 Arch Linux 上
【问题讨论】:
-
from __future__ import unicode_literals怎么样?对你来说是一种解决方法吗? -
虽然很老了,但这些天我们面临着同样的问题。你想清楚了吗?
标签: python django apache encoding mod-wsgi