python3环境下,为什么在apache2部署django会出现UnicodeEncodeError?

部署环境:
ubuntu server 16.04
apache2
python 3.6.2 (使用conda虚拟环境)
django 1.11

我在django的views.py代码里有这么一句:

    filepath = settings.PART_MESSAGE_FILEPATH + '/' + file.name

    with open(filepath, 'wb+') as new_file:
        for chunk in file.chunks():
            new_file.write(chunk)

当这个文件的名字包含中文时,就会报错,在apache的errorlog上会留下这样的记录.
文件名不包含中文的时候,就一切正常

[Wed Dec 06 13:02:58.474614 2017] [wsgi:error] [pid 2648:tid 139832153040640] WARNING 2017-12-06 13:02:58,474 /*****/views.py views.py views set_compomsg_file 183: huhai\xe4\$
[Wed Dec 06 13:25:43.729044 2017] [wsgi:error] [pid 3284:tid 139689529792256] Internal Server Error: /temrule/updatefile/
[Wed Dec 06 13:25:43.729067 2017] [wsgi:error] [pid 3284:tid 139689529792256] Traceback (most recent call last):
[Wed Dec 06 13:25:43.729070 2017] [wsgi:error] [pid 3284:tid 139689529792256]   File "/data2/serverend/comengine/templaterule/views.py", line 154, in set_compomsg_file
[Wed Dec 06 13:25:43.729072 2017] [wsgi:error] [pid 3284:tid 139689529792256]     with open(filepath, 'wb+') as new_file:
[Wed Dec 06 13:25:43.729073 2017] [wsgi:error] [pid 3284:tid 139689529792256] UnicodeEncodeError: 'ascii' codec can't encode characters in position 57-60: ordinal not in range(128)

我的conf文件

<VirtualHost *:7090>

    ServerName localhost:7090
    ServerAdmin sdfs@dsds.com


    WSGIDaemonProcess comengine python-path=/home/yangtz/anaconda3/envs/compoengine/lib/python3.6/site-packages


    WSGIProcessGroup comengine

    WSGIScriptAlias / /data2/serverend/comengine/comengine/wsgi.py


    #Directory里是项目wsgi文件的父目录,形如:/项目所处路径/dpsplat/visualplat
    <Directory /data2/serverend/comengine/comengine>
    <Files wsgi.py>
        Require all granted
    </Files>
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error-comengine.log
    CustomLog ${APACHE_LOG_DIR}/access-comengine.log combined

</VirtualHost>

我的环境明明是python3.6啊,怎么会出现UnicodeEncodeError呢?在本地runserver的时候就不会有这种事,部署到服务器 apache上就会这样,这是怎么回事?该怎么办呢?

阅读 4.9k
4 个回答

ascii表中是不包括中文的, 先encode成utf-8吧

python3虽然统一了字符串 str 的语义,并且默认采用 utf-8 的编码。但也不意味着没有编码出错的情况。你的文件应该是win下的文件,因此名称应该是win的 cp396 的,用 .encode("cp936").decode("utf-8") 吧。

看下你平台默认的是啥:

 In text mode, if encoding is not specified the encoding used is platform
 dependent: locale.getpreferredencoding(False) is called to get the
 current locale encoding. 
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题