鍍金池/ 問答/Python  Linux  網(wǎng)絡(luò)安全/ python3環(huán)境下,為什么在apache2部署django會出現(xiàn)Unicode

python3環(huán)境下,為什么在apache2部署django會出現(xiàn)UnicodeEncodeError?

部署環(huán)境:
ubuntu server 16.04
apache2
python 3.6.2 (使用conda虛擬環(huán)境)
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)

當(dāng)這個(gè)文件的名字包含中文時(shí),就會報(bào)錯(cuò),在apache的errorlog上會留下這樣的記錄.
文件名不包含中文的時(shí)候,就一切正常

[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里是項(xiàng)目wsgi文件的父目錄,形如:/項(xiàng)目所處路徑/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>

我的環(huán)境明明是python3.6啊,怎么會出現(xiàn)UnicodeEncodeError呢?在本地runserver的時(shí)候就不會有這種事,部署到服務(wù)器 apache上就會這樣,這是怎么回事?該怎么辦呢?

回答
編輯回答
青黛色

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

2017年2月19日 07:34
編輯回答
安淺陌

python3雖然統(tǒng)一了字符串 str 的語義,并且默認(rèn)采用 utf-8 的編碼。但也不意味著沒有編碼出錯(cuò)的情況。你的文件應(yīng)該是win下的文件,因此名稱應(yīng)該是win的 cp396 的,用 .encode("cp936").decode("utf-8") 吧。

2018年4月12日 12:43
編輯回答
浪蕩不羈

看下你平臺默認(rèn)的是啥:

 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. 
2017年5月11日 05:25
編輯回答
情已空

問題已經(jīng)解決了。
http://blog.csdn.net/happen23...

2017年12月21日 14:07