Django与uWSGI中的Locale UnicodeEncodeError

5 投票
2 回答
2969 浏览
提问于 2025-04-18 14:15

编辑:我刚意识到,当我不试着把那个变量打印到控制台时,它就能正常工作。为什么呢?

我遇到了一个问题,跟显示带有UTF字符的字符串标签有关。我在uwsgi的配置文件里设置了地区环境,像这样:

env =LC_ALL=en_US.UTF-8
env =LANG=en_US.UTF-8

然后在wsgi.py里:

locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')

当我运行应用代码时:

print (locale.getlocale(), locale.getpreferredencoding())
print locale.getdefaultlocale()
print "option_value", option_value
label = force_text(option_label)
print 'label', label #THIS FAILS

输出结果是:

(('en_US', 'UTF-8'), 'UTF-8')
('en_US', 'UTF-8')
option_value d
ERROR <stack trace>
print 'label', label
UnicodeEncodeError: 'ascii' codec can't encode character u'\u015b' in position 5: ordinal not in range(128)

在生产环境中通过runserver运行应用时,这个问题就不存在了。

使用的技术有:Django 1.6.5,Python 2.7.6,Ubuntu 14.04,uWSGI 2.0.5.1

2 个回答

0

在Django中,当你想使用Unicode字符,比如在表单等地方时,你必须在你想保存的Unicode前面加一个u!无论在哪里保存Unicode,都要这样做!在这个例子中,我认为是(option_label)

5

我刚刚在这里找到了解答:http://chase-seibert.github.io/blog/2014/01/12/python-unicode-console-output.html

我意识到是控制台导致了这个错误,所以在uwsgi配置文件中添加一个环境变量就能解决这个问题:env = PYTHONIOENCODING=UTF-8

撰写回答