(親手作過!!!)python
一,個人python、django、apatch2版本:apache
python:python -Vdjango
2.7.3ubuntu
django:python -c "import django; print(django.VERSION)"瀏覽器
(1, 9, 4, 'final', 0)app
apache2:/usr/sbin/apachectl -vdom
Server version: Apache/2.2.22 (Ubuntu)
Server built: Jul 24 2015 17:25:52網站
二,安裝python 和django。ui
三,安裝apache2 和 wsgi。spa
sudo apt-get insall apache2
sudo apt-get install libapache2-mod-wsgi
若是以前安裝配置過apache2的而且配置很亂,沒法修復,建議仍是徹底卸載以後再安裝。徹底卸載的命令:
sudo apt-get --purge remove apache*
sudo apt-get --purge remove apache-common
安裝完之後,去 /etc/apache2/ 下的 mods-available 和mods-enabled 中查看是否都存在 wsgi.conf 和wsgi.load 兩個文件。有則說明wsgi模塊加載到apache2成功。
四,配置apache 和 wsgi
(PS 假設你是在目錄/var/www/mysite 下面 django-admin.py startproject testproject )
我項目的tree:
一、apache的配置:
在/etc/apache2/site-available中新建一個文件 testdjango.conf (PS中文註釋都刪除)
<VirtualHost *:80> ServerName testdjango.com #ServerName這個無所謂,只要在host中把你的ip地址映射到這個上面就能夠了。不想改host最簡單的方法就是用 sudo a2dissite 000-default.conf 等虛擬主機給disable掉,只留 testdjango.conf。(PS.site-enabled中的文件是link site-availabel下的文件,若是存在link文件則是enable的,能夠根據這個來查看) DocumentRoot /var/www/mysite/testproject #這一條是指向網站的根目錄 <Directory /var/www/mysite/testproject> Order allow,deny Allow from all </Directory> WSGIDaemonProcess testdjango.com processes=2 threads=15 display-name=%{GROUP} WSGIProcessGroup testdjango.com #對應前面的ServerName
WSGIScriptAlias / /var/www/mysite/testproject/apache/django.wsgi #將後面的那個路徑指向網站的根目錄。第一個「/」表示外部訪問時的網站根目錄,當有新的requset的時候,apache從這裏開始解析。
</VirtualHost>
二、wsgi的配置
在/var/www/mysite/testproject/下新建dir:apache 。在./apache下新建文件django.wsgi。(文件名對應前面的WSGIScriptAlias第二個路徑下的文件名)
#coding:utf-8
import os import sys path = '/var/www/mysite' if path not in sys.path: sys.path.insert(0, '/var/www/mysite/testproject') #將模塊路徑加到當前模塊掃描的路徑。或sys.path.apend('/var/www/mysite/testproject')
os.environ['DJANGO_SETTINGS_MODULE'] = 'testproject.settings' #新建一個環境變量DJANGO_SETTINGS_MODULE,目的是指向django工程的settings.py,這裏
#import django.core.handlers.wsgi #old version use
#application = django.core.handlers.wsgi.WSGIHandler()
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
五,驗證
sudo a2ensite testdjango.conf #enable testjango.conf
sudo service apache2 reload (PS 若是reload時出現 apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1 for ServerName。雖然不影響但有個warning讓人不爽,能夠在/etc/apatch2/httpd.conf 中加入ServerName localhost)
最後瀏覽器 http://127.0.0.1或localhost或你ubunt的IP 就能夠看見django的初始頁面了。
其它機器的瀏覽器也能夠經過你的ubuntu的IP來查看你django的項目的頁面。
六,常見錯誤及log:
apache2的error log文件:/var/log/apache2/error.log
錯誤1:Internal Server Error 以下圖
應該是django.wsgi裏用了我註釋的 django.core.handlers.wsgi 這個方法。用下面的那個get_wsgi_application 就沒問題了。