python - 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 编码。
解决方案
推荐阅读
- vb.net - >= 消息框序列无法正常工作
- python - 在数据框中查找对应方进行计算
- spring-data-elasticsearch - 如何使用规范在 spring-data-elasticsearch 中使用 @Field 注释进行配置分析:启用:假
- selenium - 在使用相同的 xpath 定位元素时获取 InvalidSelectorException,该 xpath 在具有 1 个匹配节点的 firepath 中运行良好
- android - Android Studio 在 3.3 版的布局编辑器中禁用 textview 周围的阴影
- html - 将查询字符串从 bot 传递到 html 页面
- c# - 将对象转换为不带标题的 CSV 字符串 Servicestack CSVSerializer
- r - 在同一面板上的密度图顶部堆叠点图并让轴对齐
- javascript - 需要帮助了解函数的返回值在哪里
- gulp - 如何修复“必须指定任务函数”的 Gulp 编译错误?