首页 > 解决方案 > Python3 + uwsgi - 终端中的特殊语言字符

问题描述

我想,这个话题已经讨论过几次了,但对我来说仍然不清楚。首先,我从使用过的操作系统开始:我在 Ubuntu 16.04 LTS 上使用远程 shell。/etc/default/locale 下面:

#  File generated by update-locale
LANG=en_US.UTF-8
#LANG=pl_PL.UTF-8
#LANGUAGE=POSIX

我有一些 py 文件:test4.py

# -*- coding: utf-8 -*-

import sys

va =  sys.getfilesystemencoding()
print('File system encoding')
print(va)

vb = sys.getdefaultencoding()
print('Default encoding')
print(vb)

dict = {'foo' : 'bar',
        'cebula' : 'łąśćźżęó'
        }

for key, value in dict.items():
        print(key + ' : ' + value)

当我尝试调用此文件时:

File system encoding
ascii
Default encoding
utf-8
foo : bar
Traceback (most recent call last):
File "test/test4.py", line 18, in <module>
print(key + ' : ' + value)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 9-16: ordinal not in range(128)

如果在调用脚本之前,我使用:

export PYTHONIOENCODING=UTF-8

然后,我运行脚本:

File system encoding
ascii
Default encoding
utf-8
cebula : łąśćźżęó
foo : bar

一切正常。

所以,我将使用 uwsgi 运行我的 Django 应用程序(不管我是否在 virtualenv 中运行它)。在 *.ini 文件(配置)上,我有块:

env = PYTHONIOENCODING=UTF-8

脚本代码(已删减,仅用于显示正在发生的事情):

# -*- coding: utf-8 -*-

def command(request):

    if request.method == 'POST':
        for key, value in sorted(request.POST.items()):
            print(key + ' : ' + value)

如果value具有特定于语言的字母(在这种情况下 - 波兰语):

print(key + ' : ' + value)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 10-12: ordinal not in range(128)

如果我添加到uwsgi.ini以下行:

env = LC_ALL=pl_PL.UTF-8或者env = LANG=pl_PL.utf-8

该应用程序运行稳定。

问题:

a) 为什么 Python3 不需要设置这个语言环境,即使是临时的,但 uwsgi 需要它们来正确解析特定于语言的字符?

b) 当我知道可打印变量将显示在终端中(如上)并且它们将包含特定于语言的字符时,我应该使用哪个函数/方法。我想继续使用 en_US.UTF-8 编码。

标签: pythonencodingterminaluwsgiutf

解决方案


推荐阅读