django是一款基於python語言的WEB開源框架,本文給出瞭如何將基於django寫的python網站部署到window的IIS上。python
筆者的運行環境:web
Window xp sp3django
IIS 5.1api
Python 2.7.2 (http://www.python.org/)瀏覽器
pywin32-217.win32-py2.7 (python的win32擴展)app
Django-1.3.1 (https://www.djangoproject.com/)框架
isapi_wsgi-0.4.2-py2.5 (http://code.google.com/p/isapi-wsgi/ ,基於IIS的ISAPI擴展的WSGI實現).網站
setuptools-0.6c11.win32-py2.7 this
原理解釋:google
IIS經過ISAPI能夠擴展支持其餘語言實現的WEB應用,isapi_wsgi-0.4.2-py2.5這個程序做爲ISAPI實現了WSGI規範,
WSGI規範是做爲python web應用與web服務容器之間的接口規範,經過這個程序,對IIS的某個虛擬站點的請求就能夠定向
到這個ISAPI去處理,而無需爲了去部署到某個特定容器裏而去改動python web的任何代碼。
步驟
先安裝好IIS, Python, Django, setuptools, pywin32, 這些很簡單。(將環境變量PATH里加入python的安裝主目錄)
下載isapi_wsgi-0.4.2-py2.5.egg文件 (這是python裏的一種安裝包,相似於Red Hat的RPM,固然你也能夠下載exe或zip下載安裝)
下載後,在命令行窗口輸入:easy_install isapi_wsgi-0.4.2-py2.5.egg (這裏它會提示你安裝成功,注意:必須安裝setuptools才能運行該命令)
寫一個部署腳本,名字假定爲wsgi_deploy.py (假定你的web project 目錄爲 C:\Web, 在Web目錄下有一個App爲mysite) ,目錄必定不要弄錯,不然容易出現HTTP 500錯誤。
import os, sys
sys.path.append(‘C:\\Web')
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()import isapi_wsgi
# The entry points for the ISAPI extension.
def __ExtensionFactory__():
return isapi_wsgi.ISAPISimpleHandler(application)if __name__=='__main__':
# If run from the command-line, install ourselves.
from isapi.install import *
params = ISAPIParameters()
# Setup the virtual directories - this is a list of directories our
# extension uses - in this case only 1.
# Each extension has a "script map" - this is the mapping of ISAPI
# extensions.
sm = [
ScriptMapParams(Extension="*", Flags=0)
]
vd = VirtualDirParameters(Name="mysite",
Description = "ISAPI-WSGI ISAPISimpleHandler Django mysite",
ScriptMaps = sm,
ScriptMapUpdate = "replace"
)
params.VirtualDirs = [vd]
HandleCommandLine(params)
5. 在命令行輸入: wsgi_deploy.py install ,運行以後會在IIS上建立上面腳本定義的虛擬路徑"mysite", 同時你會發現一個'_wsgi_deploy.dll'文件會建立出來,這個就是ISAPI。
細心的讀者不妨在IIS的"mysite「的設置裏去查看下就明白了。
6.部署後,既能夠經過瀏覽器訪問你的Web App了
注:若是出現錯誤,如何處理?
能夠在命令行輸入: python -m win32traceutil 即可以輸出isapi_wsgi模塊輸出的錯誤堆棧信息
一般錯誤都是出如今路徑方面。如相似於
ImportError: Could not import settings 'mysite.settings' (Is it on sys.path?): N
o module named mysite.settings 這樣的問題。
這樣的狀況,須要去找到上述的部署腳本wsgi_deploy.py,去修改成正確的配置,而後記住須要先運行
wsgi_deploy.py remove後再運行wsgi_deploy.py install。