甚至在设置LANG和LC_ALL之后,在mod_wsgi中运行时出现UnicodeEncodeError

时间:2015-06-04 04:07:17

标签: python unicode utf-8 flask

从我的应用程序打印unicode字符串时出现UnicodeEncodeError错误。它通过AWS上的Elastic Beanstalk运行(Apache + mod_wsgi)。我发现this很有用,当我致电locale.getdefaultlocale()locale.getpreferredencoding()时,我得到NoneASCII

我将LANGLC_ALL设置为en_US.UTF-8(通过WSGIDaemonProcess指令AND环境变量)。现在,当我拨打locale.getdefaultlocale()locale.getpreferredencoding()时,我会收到('en_US', 'UTF-8')UTF-8。但是,我仍然得到相同的UnicodeEncodeError

sys.stdout的类型为mod_wsgi.Log。我找不到有关如何检查/设置此编码的任何细节。

我不知道如何继续调试。如何解决此错误?

这个wsgi.conf是Elastic Beanstalk的默认设置,除了我将langlocale添加到WSGIDaemonProcess指令的地方。

LoadModule wsgi_module modules/mod_wsgi.so
WSGIPythonHome /opt/python/run/baselinenv
WSGISocketPrefix run/wsgi
WSGIRestrictEmbedded On

<VirtualHost *:80>
    Alias /static/ /opt/python/current/app/static/

    <Directory /opt/python/current/app/static/>
        Order allow,deny
        Allow from all
    </Directory>

    WSGIScriptAlias / /opt/python/current/app/application.py

    <Directory /opt/python/current/app/>
        Require all granted
    </Directory>

    WSGIDaemonProcess wsgi processes=1 threads=15 lang='en_US.UTF-8' locale='en_US.UTF-8' display-name=%{GROUP} python-path=/opt/python/current/app:/opt/python/run/venv/lib/python2.7/site-packages user=wsgi group=wsgi home=/opt/python/current/app
    WSGIProcessGroup wsgi
</VirtualHost>

回溯:

ERROR:discotech:Exception on /venues [GET]
Traceback (most recent call last):
  File "/opt/python/run/venv/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "/opt/python/run/venv/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/opt/python/run/venv/lib/python2.7/site-packages/flask_cors/extension.py", line 110, in wrapped_function
    return cors_after_request(app.make_response(f(*args, **kwargs)))
  File "/opt/python/run/venv/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/opt/python/run/venv/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
    rv = self.dispatch_request()
  File "/opt/python/run/venv/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/opt/python/current/app/discotech/api/venue.py", line 32, in get_venues
    print "TEST = %s", test
UnicodeEncodeError: 'ascii' codec can't encode character u'\\xe1' in position 1: ordinal not in range(128)

以下是我用来练习它的代码:

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

...

@api_app.route('/venues')
def get_venues():
    test = u"Ián"
    print "TEST =", test

1 个答案:

答案 0 :(得分:1)

我遵循@kchomski的建议并编辑了/etc/apache2/envvars

## Uncomment the following line to use the system default locale instead:
. /etc/default/locale

最后一行已发表评论,我未评论它。现在我的WSGI脚本正在使用en_US.UTF-8语言环境,并且一切正常!