先大概介紹一下: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 # 空行,告訴服務器結束頭部