python3使用apache WSGI默认编码UnicodeDecodeError ascii

Web*_*ube 7 python apache encoding utf-8 web.py

import locale
prefered_encoding = locale.getpreferredencoding()
prefered_encoding 'ANSI_X3.4-1968'
Run Code Online (Sandbox Code Playgroud)

我正在使用一个名为inginious的框架,它正在使用web.py来呈现其模板.

web.template.render(os.path.join(root_path, dir_path),
                                   globals=self._template_globals,
                                   base=layout_path)
Run Code Online (Sandbox Code Playgroud)

渲染在我的本地主机上运行,不在我的临时服务器上运行.

他们都运行python3.我看到web.py强制执行utf-8

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

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

这是堆栈跟踪

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),
Run Code Online (Sandbox Code Playgroud)

我的html包括hebew chars,小例子

<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>
Run Code Online (Sandbox Code Playgroud)

我这样打开它:

open('/path/to/feedback.html').read()
Run Code Online (Sandbox Code Playgroud)

并且编码失败的行是希伯来字符所在的行.

我试过设置一些环境变量~/.bashrc:

export PYTHONIOENCODING=utf8
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
export LANGUAGE=en_US.UTF-8
Run Code Online (Sandbox Code Playgroud)

在用户之下 centos

巧妙的框架安装pip在python3.5网站包下.它由用户下的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'
Run Code Online (Sandbox Code Playgroud)

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

SetEnv LC_ALL en_US.UTF-8
SetEnv LANG en_US.UTF-8
SetEnv LANGUAGE en_US.UTF-8
SetEnv PYTHONIOENCODING utf8
Run Code Online (Sandbox Code Playgroud)

并重新启动使用sudo service httpd restart,但仍然没有运气.

我的问题是,解决这个问题的最佳做法是什么.我知道有这方面的黑客,但我想了解什么是下划线原因以及如何解决它.

谢谢!

Web*_*ube 1

终于在读取文件更改时找到了答案

open('/path/to/feedback.html').read()
Run Code Online (Sandbox Code Playgroud)

import codecs
with codecs.open(file_path,'r',encoding='utf8') as f:
     text = f.read()
Run Code Online (Sandbox Code Playgroud)

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