1.Apache + CGI的架構圖
2.Apache + Python CGI的開發和配置方法
(1)安裝apache
執行命令yum install httpd即可完成apache的安裝,確保apache配置/etc/httpd/conf/httpd.conf中包含如下配置:
ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"
<Directory "/var/www/cgi-bin">
AllowOverride None
Options +ExecCGI
Order allow,deny
Allow from all
</Directory>
AddHandler cgi-script .cgi .pl .py
備註:ScriptAlias指定了python cgi腳本的存放目錄爲/var/www/cgi-bin/,且用戶訪問的方式爲http://ip:port/cgi-bin/XXX;<Directory "/var/www/cgi-bin">配置了cgi腳本目錄的可執行權限;AddHandler cgi-script指令配置可以支持的cgi腳本文件的後綴。
(2)編寫Python CGI腳本
舉例來說,
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Desc: python common cgi
Date: 2017-11-23
Author: xxxx
"""
import time
#定義全局變量
nowtime = ''
def initData():
"""用來獲取填充html頁面的數據
"""
global nowtime
nowtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
def genHtml2():
"""生成HTML頁面, 使用三個雙引號,使Python中的HTML頁面更美觀
"""
print 'Content-type:text/html'
print
print """
<html>
<head>
<meta charset="utf-8">
<title>Python CGI DEMO程序</title>
</head>
<body>
<h1>This is DEMO~~~~</h1>
</body>
</html>
"""
def genHtml():
"""生成HTML頁面
"""
print "Content-type:text/html"
print
print '<html>'
print '<head>'
print '<meta charset="utf-8">'
print '<title>Python CGI DEMO程序</title>'
print '</head>'
print '<body>'
print '<h2>當前時間爲: %s</h2>' % nowtime
print '</body>'
print '</html>'
def main():
"""CGI入口
"""
#初始化環境
initData()
#生成頁面
genHtml()
if __name__ == '__main__':
main()
備註:可以將該文件命名爲xxx.cgi,xxx.py等等都是可以的。這個腳本可以成任何的腳本語言哦,例如perl,shell,C以及C++等等。
學習資料參考於: