在IIS服务器上以CGI方式运行Python脚本的教程

WBOY
Release: 2016-06-10 15:14:16
Original
1176 people have browsed it

由于接触到Python Web开发,正好把最简单的CGI方式研究了一下,话说在Windows下配置Python的Web开发还真的蛮麻烦的,Linux下配置倒挺容易,正好微软有技术文章《Using Python Scripts with IIS》介绍了这些内容,此文介绍了两种方法,一是使用ASP引擎来运行Python脚本,这个可能需要用到ActivePython,当然ASP技术已经过时了,我今天就简单介绍下CGI模块运行方式。

编写简单的支持CGI的Python脚本(本文介绍3.2版本的Python):

print("Status: 200 OK")
print("Content-type: text/html")
print() # 打印一行空白行,用于分隔HTTP Header和正文
 
print("<h1>Hello World!</h1>")

Copy after login

这样就可以了,大家可以猜出CGI是将标准输出流重新定向到HTTP输出流来实现网页或者数据传输的。

当然这个在IIS中是不能直接运行的,我们需要配置一下,打开Internet 信息服务(IIS)管理器界面,选择“处理程序映射”。

2015425161112268.png (373×139)

在接下来出现的界面右侧选择“添加模块映射”。

IIS7添加模块映射

2015425161152223.png (572×250)

假设我们的Python 3.2安装于C:\Python32,那么可以向下图这样填写:

2015425161216044.png (397×318)

然后点击确定,在接下来出现的对话框选择“是”。

2015425161237176.png (416×161)

好了,我们的配置完成了,重启一下IIS,然后赶快试试刚才的代码吧。可能有人会抱怨,用CGI编写网页一旦报错调试会比较麻烦,比如报下面的错误:

HTTP 错误 502.2 - Bad Gateway

指定的 CGI 应用程序由于未返回完整的一组 HTTP 头而产生错误行为。它实际返回的头是“Traceback (most recent call last): File "E:\projects\test.py", line 3, in 1/0 ZeroDivisionError: division by zero ”。

其实我们只需要在最开始引入import cgitb; cgitb.enable()就可以了,就像下面这样:

import cgitb; cgitb.enable()
print("Status: 200 OK")
print("Content-type: text/html")
print() # 打印一行空白行,用于分隔HTTP Header和正文
 
print("<h1>Hello World!</h1>")

Copy after login

这样一旦出错,就会以友好的方式将错误输出来。

2015425161301420.png (610×391)

对于表单的处理,可以参考import cgi模块(cgi.FieldStorage),网上有很多此方面的介绍,我就不多说了,Enjoy it!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!