使用wsgi模塊將Django加於apache

1. WSGI模塊的編譯和安裝:

首先,從code.google下載mod_wsgi-3.4.tar.gz源碼包。

解壓並進入目錄運行"./configure --with-apxs=/usr/local/apache2/bin/axps  --with-python=/usr/local/bin/python",其中這兩個with分別用於制定apache安裝文件的axps路徑,和python解釋器的路徑。在運行make的時候,它們都會被用到。

運行make。出現如下錯誤:“apxs:fatal error: Python.h No such file or directory"。解決辦法,安裝python-devel包。

make install, 完成安裝。

2. 配置apache的http.conf

增加一行,"LoadModule wsgi_module    modules/mod_wsgi.so"

增加一行,“WSGIScriptAlias /mysite  /home/djweb/mysite/mysite/wsgi.py" #這個路徑是用django-admin.py startproject mysite時自動創建的wsgi.py的路徑。

增加一行,“WSGIPythonPath  /home/djweb/mysite" #這是站點的路徑,這個還是挺有用的。其實,是在sys.path中增加一個路徑項。

#如果apache的error日誌中有如下錯誤,”Execption occured processing WSGIScript '/home/djweb/mysite/mysite/wsgi.py", "could not import settings 'mysite.settings'"時,就是sys.path中並沒有包含“/home/djweb/mysite"這個路徑。這時可以增加這一行解決,或者想辦法在sys.path中永久地增加這個路徑。(PYTHONPATH,或者site-packages/目錄下增加一個mysite.pth)

設置權限:apache2.2和apache2.4相比,有些不同。下面的是2.2的配置:

<Directory /home/djweb/mysite/mysite> 

Order deny, allow

Allow from all

</Directory>

可能遇到403錯誤,error日誌裏有 ”(13)Permission denied: access to /dj denied (filesystem path '/home/...') because search permissions are missing on a component of the path“。這是由於目標目錄上的每個目錄都需要有執行權限。chmod a+x給每個目錄增加執行權限,可解決這個問題。

2.4的配置如下:

<Directory /home/djweb/mysite/mysite> 

Require all granted         #否則會出現403的錯誤, error日誌裏有" AH01630: client denied by server configuration

</Directory>


3. 到這裏,重啓apache服務, 就可以通過http://localhost/mysite訪問了。看到下面,就成功了。

It worked!

Congratulations on your first Django-powered page.

4. wsgi.py文件說明。

默認情況下,這個文件其實就做兩件事情。

os.environ.setdefault(“DJANGO——SETTINGS——MODULE”, “mysite.settings")#導入設置文件

from django.core.wsgi import get_wsgi_applicatioin

application = get_wsgi_application() #創建一個叫做application的對象,WSGI服務會使用它。


我們可以自己寫一個簡單的測試一下:

def appication(environ, start_response):

    status = '200 OK'

    output = 'Hello World!'

    response_headers = [('content-type', 'text/plain'),

                                             ('content-length', str(len(output)))]

    start_response(status, response_headers)

    return [output]

用這個替換wsgi.py,就會看到“Hello World"了。

5.wsgi的運行模式

默認情況下,wsgi是運行在embeded的模式下,即在apache的worker進程內。對wsgi application的修改,需要重啓apache才能生效。

另外一種模式是daemon模式,wsgi運行在獨立的進程內,wsgi的代碼改變時,不需要重啓apache就能生效。目前,還沒有深入研究這兩個的區別和具體用法。


總結:堅持寫博文,不容易啊。挺花時間的,但是,好處是可以讓自己的思路便清晰點。最重要的,還是記錄自己這個成長的過程,記錄遇到的問題,也許對他人也有用呢。現在,還只是在起步的皮毛階段。加油啊!


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章