1. 程式人生 > >django 16、用apache+mod_wsgi部署後中文亂碼的解決方法

django 16、用apache+mod_wsgi部署後中文亂碼的解決方法

問題的起因是:自己通過python manage.py runserver 0.0.0.0:8082這種方式開啟專案,中文不會亂碼,但是樓主自己也在阿里雲上部署了一個網站,通過django+apache+mod_wsgi+ubuntu這樣的環境下配置的,卻會出現中文亂碼錯誤,

好幾個月沒有解決這個問題。

今天專案要新增上傳中文檔案,結果又碰到這種情況,本地伺服器可以,阿里雲伺服器又不行,於是狠下心一定要幹掉這個問題。下面無償奉獻出解決方法。

If you get a UnicodeEncodeError

If you’re taking advantage of the internationalization features of Django (see 

Internationalization and localization) and you intend to allow users to upload files, you must ensure that the environment used to start Apache is configured to accept non-ASCII file names. If your environment is not correctly configured, you will trigger UnicodeEncodeErrorexceptions when calling functions like the ones in 
os.path
 on filenames that contain non-ASCII characters.

To avoid these problems, the environment used to start Apache should contain settings analogous to the following:

export LANG='en_US.UTF-8'
export LC_ALL='en_US.UTF-8'

Consult the documentation for your operating system for the appropriate syntax and location to put these configuration items; /etc/apache2/envvars is a common location on Unix platforms. Once you have added these statements to your environment, restart Apache.

也就是需要在:

/etc/apache2/envvars中新增:

export LANG='en_US.UTF-8'
export LC_ALL='en_US.UTF-8'

 新增完後執行apache2服務重新啟動命令

sudo service apache2 restart

另外順帶把django上傳帶有中文名字檔案報錯UnicodeEncodeError的問題也給你們解決了,

解決方法:執行下面的命令,把search替換成你的網站專案目錄即可,

sudo chmod g+w -R search/

sudo chgrp www-data -R search/

注意:不要漏掉 -R , 這是遞迴賦予寫許可權,否則仍然報錯,不要漏了/

找了幾個月的各種資料,文件,就解決了這兩個很重要的問題,天道酬勤!