先大概介绍一下:Python CGI编程html
CGI 目前由NCSA维护,NCSA定义CGI以下:python
CGI(Common Gateway Interface),通用网关接口,它是一段程序,运行在服务器上如:HTTP服务器,提供同客户端HTML页面的接口。linux
为了更好的了解CGI是如何工做的,咱们能够从在网页上点击一个连接或URL的流程:web
CGI程序能够是Python脚本,PERL脚本,SHELL脚本,C或者C++程序等。shell
下面说重点:apache
下面配置以wampserver版的apache为例,其余版本应该大同小异的。编程
1.找到apache配置文件httpd.conf ,去掉下面代码前面的#号windows
LoadModule cgi_module modules/mod_cgi.so
2.找到浏览器
#
# "d:/wamp/bin/apache/apache2.4.9/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
下面的相似这样的一段代码服务器
<Directory "d:/wamp/bin/apache/apache2.4.9/cgi-bin"> AllowOverride None Options None Require all granted </Directory>
改成:
<Directory "E:/test/python/cgi/"> AllowOverride None Options Indexes FollowSymLinks ExecCGI Require all granted Require host ip </Directory>
E:/test/python/cgi/ 这个是你的.py文件存放目录
设置CGI的访问权限和路径
3.找到:
相似:
ScriptAlias /cgi-bin/ "d:/wamp/bin/apache/apache2.4.9/cgi-bin/"
改成:
ScriptAlias /cgi-bin/ "E:/test/python/cgi/"
E:/test/python/cgi/ 这个是你的.py文件存放目录
4.找到
#AddHandler cgi-script .cgi
替换为:
AddHandler cgi-script .cgi .py
这样就能够支持python的.py文件,若是你须要解释shell的脚本文件,能够添加.pl
到此为止基本配置成功了web服务器了。
py文件里面须要注意如下几点:
#!D:\Program Files\python27\python.exe # -*- coding: utf-8 -*- print "Content-type:text/html" print # 空行,告诉服务器结束头部 print '<html>' print '<head>' print '<meta charset="utf-8">' print '<title>Hello Word - 个人第一个 CGI 程序!</title>' print '</head>' print '<body>' print '<h2>Hello Word! 我是CGI程序</h2>' print '</body>' print '</html>'
前面4行很是必要,不然可能报错
#!D:\Program Files\python27\python.exe 这个是指名python解释器(windows下的,linux下的相似 #!/usr/bin/env python )
# -*- coding: utf-8 -*- 指定页面编码
print "Content-type:text/html" 指定文件类型
print # 空行,告诉服务器结束头部