当我们在编程的时候,要将CherryPy3与IIS 6.0集成,可以使用ISAPI_WSGI模块。ISAPI_WSGI是一个用于在IIS中运行WSGI应用程序的模块。首先要确保自己的服务器上安装了Python和CherryPy3。并且下载最新的ISAPI_WSGI模块。具体实际操作可以看看下文,这是我呕心沥血几个通宵写出来的代码。
1、问题背景
- 在采用 CherryPy 框架的小型 Python Web 应用程序中,需要在 Windows 2003 和 IIS 6.0 环境下进行部署。
- 尽管在 Ubuntu 服务器上使用 mod_python 与 Apache 结合的方式成功运行了 CherryPy,但在 Windows 环境下遇到了困难。
- 尝试了各种解决方案,例如安装 Python 2.6、CherryPy 3、ISAPI-WSGI 和 PyWin32,并阅读了相关文档,但仍然无法成功运行应用程序。
2、解决方案
- 首先需要了解在 IIS 中运行 ISAPI 应用程序的基本流程。
- 可以尝试先让一个简单的 Hello World WSGI 应用程序在 ISAPI_WSGI 下运行。
- 接下來需要編寫一個鉤子腳本,以便讓 IIS 可以加載 DLL,並創建一個 CherryPy WSGI 實例。
- 最後,需要將腳本放置在 inetpub\cherrypy 目錄中,並運行它,即可將其安裝到 IIS 網站的根目錄中。
- 另外,需要在 config.py 文件中添加以下配置:
cherrypy.config.update({
'tools.sessions.on': True
})
- 完成上述步骤后,CherryPy 应用程序即可在 IIS 6.0 环境下正常运行。
以下代码示例展示了如何创建钩子脚本:
import sys
import os
import isapi_wsgi
# change this to '/myapp' to have the site installed to only a virtual
# directory of the site.
site_root = '/'
if hasattr(sys, "isapidllhandle"):
import win32traceutil
appdir = os.path.dirname(__file__)
egg_cache = os.path.join(appdir, 'egg-tmp')
if not os.path.exists(egg_cache):
os.makedirs(egg_cache)
os.environ['PYTHON_EGG_CACHE'] = egg_cache
os.chdir(appdir)
import cherrypy
import traceback
class Root(object):
@cherrypy.expose
def index(self):
return 'Hai Werld'
def setup_application():
print "starting cherrypy application server"
#app_root = os.path.dirname(__file__)
#sys.path.append(app_root)
app = cherrypy.tree.mount(Root(), site_root)
print "successfully set up the application"
return app
def __ExtensionFactory__():
"The entry point for when the ISAPIDLL is triggered"
try:
# import the wsgi app creator
app = setup_application()
return isapi_wsgi.ISAPISimpleHandler(app)
except:
import traceback
traceback.print_exc()
f = open(os.path.join(appdir, 'critical error.txt'), 'w')
traceback.print_exc(file=f)
f.close()
def install_virtual_dir():
import isapi.install
params = isapi.install.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 = [
isapi.install.ScriptMapParams(Extension="*", Flags=0)
]
vd = isapi.install.VirtualDirParameters(
Server="CherryPy Web Server",
Name=site_root,
Description = "CherryPy Application",
ScriptMaps = sm,
ScriptMapUpdate = "end",
)
params.VirtualDirs = [vd]
isapi.install.HandleCommandLine(params)
if __name__=='__main__':
# If run from the command-line, install ourselves.
install_virtual_dir()
通过上述解决方案,可以成功将 CherryPy 应用程序集成到 IIS 6.0 环境中,并使其正常运行。
根据上述的步骤,我们可以将CherryPy3应用程序与IIS 6.0集成,实现在IIS中运行CherryPy3应用程序的功能。但是这里需要注意的是,IIS 6.0已经比较老旧,建议升级到更新的版本以获得更好的性能和安全性。如有任何不懂的问题可以留言讨论。