python3默认编码UnicodeDecodeError ascii使用apache WSGI

标签 python apache encoding utf-8 web.py

import locale
prefered_encoding = locale.getpreferredencoding()
prefered_encoding 'ANSI_X3.4-1968'

我正在使用一个名为 inginious 的框架它正在使用 web.py渲染它的模板。

web.template.render(os.path.join(root_path, dir_path),
                                   globals=self._template_globals,
                                   base=layout_path)

渲染在我的本地主机上运行在我的暂存服务器上不运行

它们都运行 python3。我看到 web.py 在

上强制执行 utf-8

仅 Python2 中的编码(这不在我手中)

def __str__(self):
    self._prepare_body()
    if PY2:
        return self["__body__"].encode('utf-8')
    else:
        return self["__body__"]

这是堆栈跟踪

t = self._template(name),
File "/lib/python3.5/site-packages/web/template.py", line 1028, in _template,
self._cache[name] = self._load_template(name),
File "/lib/python3.5/site-packages/web/template.py", line 1016, in _load_template
return Template(open(path).read(), filename=path, **self._keywords)
File "/lib64/python3.5/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 83: ordinal not in range(128),

我的 html 包含希伯来语字符,小例子

<div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        <h4 class="modal-title feedback-modal-title">
                            חישוב האיברים הראשונים בסדרה של איבר ראשון חיובי ויחס שלילי:
                            <span class="red-text">אי הצלחה</span>

然后我像这样打开它:

open('/path/to/feedback.html').read()

编码失败的行是希伯来字符所在的位置。

我尝试在 ~/.bashrc 中设置一些环境变量:

export PYTHONIOENCODING=utf8
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
export LANGUAGE=en_US.UTF-8

在用户centos

巧妙的框架作为pip安装在python3.5 site-packages下。它由用户 apache

下的 apache 服务器提供服务

尝试在代码中设置环境变量(在应用程序初始化期间),以便 apache WSGI 能够识别它们

import os 
os.environ['LC_ALL'] = 'en_US.UTF-8'
os.environ['LANG'] = 'en_US.UTF-8'
os.environ['LANGUAGE'] = 'en_US.UTF-8'

我已经使用 setenv 编辑了 /etc/httpd/conf/httpd.conf方法:

SetEnv LC_ALL en_US.UTF-8
SetEnv LANG en_US.UTF-8
SetEnv LANGUAGE en_US.UTF-8
SetEnv PYTHONIOENCODING utf8

并使用 sudo service httpd restart 重新启动,但仍然没有成功。

我的问题是,解决这个问题的最佳做法是什么。我知道有一些技巧可以解决这个问题,但我想了解下划线的原因是什么以及如何解决它。

谢谢!

最佳答案

终于在阅读文件时找到了答案 改自

open('/path/to/feedback.html').read()

import codecs
with codecs.open(file_path,'r',encoding='utf8') as f:
     text = f.read()

如果有人有更通用的方法可行,我会接受他的回答

关于python3默认编码UnicodeDecodeError ascii使用apache WSGI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46703221/

相关文章:

apache - Yii + EasyPHP 运行时路径不可写?

python - Django 编码/解码问题

python - Python3日历模块Unicode错误

python - Pandas Multiindex 到单列中的月日格式

python - GPflow 和 Sklearn 计算的 PCA 不匹配

python - Tensorflow 中的反向传播(通过时间)代码

java - Apache Camel 中的解码 (JSON)

python - np.mean() 导致内存不足错误

Django + WSGI : Refreshing Issues?

python - 无法解析 Google Play 应用评分数据